× Back Moving from C to C++ setw and endl manipulator String Scope resolution operator Inline function Function overloading Function Overriding Default Arguments Parameter Passing Techniques in C++ Recursion Structures
Next Topic → ← Previous Topic

Moving from C to C++

               
printf("Hello world"); // this is in C language
cout << "Hello world"; // this is in C++ language 

scanf("&d",&a); // inputing value in a variable in C language
cin>>a; // inputing value in a variable in C++ language
               
           

Adding two numbers in C and C++ language

                                     
// C 
#include <stdio.h>
int main()
{
    int a, b, sum = 0;
    printf("Enter the value of a : ");
    scanf("%d", &a);
    printf("Enter the value of b : ");
    scanf("%d", &b);
    sum = a + b;
    printf("The sum is : %d", sum);
    return 0;
}
                   
               
                                  
// C++
#include <iostream>
using namespace std;
int main()
{
    int a, b, sum;
    cout << "Enter the value of a : ";
    cin >> a;
    cout << "Enter the value of b : ";
    cin >> b;
    sum = a + b;
    cout << "The sum is : " << sum;
    return 0;
}
                   
               

The major parts of C++ include:

  1. Basic syntax and data types: C++ has a similar syntax and data types as C, including primitive data types like integers, floats, and characters, as well as more advanced data types like arrays, structures, and classes.
  2. Object-oriented programming: C++ is an object-oriented programming language, which means that it supports the concepts of classes, objects, inheritance, and polymorphism. These concepts allow for the creation of modular, reusable, and extensible code.
  3. Templates: C++ supports templates, which allow developers to write generic code that can be reused with different data types. Templates are used extensively in the standard library of C++, which provides a wide range of generic algorithms and data structures.
  4. Standard Library: C++ provides a rich set of libraries, including the Standard Template Library (STL) which contains a wide range of containers like vectors, maps, and sets, as well as algorithms like sorting and searching.
  5. Input/Output: C++ provides a comprehensive set of input/output facilities, including support for file handling, stream-based input/output, and formatting.
  6. Multi-threading: C++ supports multi-threading, allowing developers to write concurrent programs that can take advantage of modern multi-core processors.

setw and endl manipulator

Example code which shows use of setw() and endl ↓

                                     
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int num = 123;

    cout << "Without using setw :" << num << "\n";
    // Using setw() manipulator to set the width of the output field to 10
    cout << "With using setw :" << setw(10) << num << "\n";

    // Using endl manipulator to insert a newline
    cout << "This is on one line." << endl;
    cout << "This is on another line." << endl;

    return 0;
}
                   
               

Output ↓

                   
Without using setw :123
With using setw :       123
This is on one line.
This is on another line.
                   
               

Strings

string keyword is used for declaration of a string datatype.

                
char name[20] = "Henry"; // C programming
                
            
                
string name = "Henry"; // C++ programming
                
            

Inputing and outputing string ↓

                   
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "Hello, " << name << "!";
    return 0;
}
                   
               

Program to demonstrate basic operation using string ↓

                   
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string myString = "Hello, world!";

    // manipulating string
    // Accessing characters: You can access individual characters in a string using the indexing operator or the at() member function.
    char firstChar = myString[0];     // Access the first character
    char secondChar = myString.at(1); // Access the second character

    // Concatenation: You can concatenate strings using the + operator or the append() member function.
    string name = "John";
    string greeting = "Hello, " + name; // Concatenate strings
    greeting.append("!");

    // Length: You can obtain the length of a string using the length() or size() member functions.
    int len = myString.length();  // Get the length of the string

    return 0;
}
                   
               

Scope resolution operator

Program to access the hidden value using the scope resolution (::) operator

                                       
#include <iostream>
using namespace std;

// declare global variable 
int num = 50;
int main()
{
    // declare local variable
    int num = 100;

    // print the value of the variables
    cout << "The value of the local variable num : " << num;

    // use scope resolution operator (::) to access the global variable 
    cout << "\n The value of the global variable num : " << ::num;
    return 0;
}
                       
                   

Output ↓

                       
The value of the local variable num : 100
The value of the global variable num : 50
                       
                   

Use of the scope resolution Operator

  1. It is used to access the hidden variables or member functions of a program.
  2. It defines the member function outside of the class using the scope resolution.
  3. It is used to access the static variable and static function of a class.
  4. The scope resolution operator is used to override function in the inheritance.

Inline function

Syntax ↓

                          
inline return-type function-name(parameters)
{
    // function code
}
                   
               

Example ↓

                   
#include <iostream>
using namespace std;
inline int cube(int s) { return s * s * s; }
int main()
{
    cout << "The cube of 3 is : " << cube(3) << endl;
    return 0;
}
                   
               

Function Overloading

Example ↓

                      
void area(int a);
void area(float a);
void area(int a, int b);
void area(float a, int b);
void area(int a, float b);
void area(float a, float b, float c);
void area(int a, int b, int c);
                   
               

Program to demonstrate function overloading ↓

                        
#include <iostream>
using namespace std;
int area(int);
float area(float);
int area(int, int);
double area(double);
int main()
{
    cout << "Area of square is : " << area(5) << endl;
    // cout << "Area of square  in floating point is : " << area(5.7) << endl; // this is not working properly
    cout << "Area of square  in floating point is : " << area((float)5.7) << endl;
    cout << "Area of rectangle is : " << area(5, 10) << endl;
    cout << "Area of circle is : " << area(3.8) << endl;
    return 0;
}
int area(int a)
{
    return a * a;
}
float area(float a)
{
    return a * a;
}
int area(int a, int b)
{
    return a * b;
}
double area(double a)
{
    return (314 * a * a) / 100;
}
                        
                    

Function Overriding

Syntax ↓

                   
class class-name
{
    void fun()
    {
        ...
    }
};
class class-name : public base-class
{
    void fun()
    {
        ...
    }
};
                   
               

Default Arguments

                   
// CPP Program to demonstrate Default Arguments
#include <iostream>
using namespace std;
    
// A function with default arguments,
// it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0
{
    return (x + y + z + w);
}
    
// Driver Code
int main()
{
    // Statement 1
    cout << sum(10, 15) << endl;
    
    // Statement 2
    cout << sum(10, 15, 25) << endl;
    
    // Statement 3
    cout << sum(10, 15, 25, 30) << endl;
    return 0;
}
                   
               

Output ↓

                                    
25
50
80
                   
               

Parameter Passing Techniques in C++

Terminology ↓

Important methods of Parameter Passing

Pass By Value

  • Changes made to formal parameter do not get transmitted back to the caller.
  • Any modifications to the formal parameter variable inside the called function or method will not be reflected in the actual parameter in the calling environment. This method is also called as call by value.
                                               
// call by value
#include <iostream>
using namespace std;
void increment(int a)
{
    a++;
    cout << "Value of a in increment function : " << a << endl;
}
int main()
{
    int a = 0;
    // passing parameters
    increment(a);
    cout << "Value of a in main function : " << a << endl;
    return 0;
}
                           
                       

output ↓

                           
Value of a in increment function : 1
Value of a in main function : 0
                           
                       

Pass by address

  • Changes made to formal parameter do get transmitted back to the caller through parameter passing.
  • Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual data. This method is also called as call by address.
                           
#include <iostream>
using namespace std;
void increment(int *a)
{
    // (*a)++; or
    *a = *a + 1;
    cout << "Value of a in increment function : " << *a << endl;
}
int main()
{
    int a = 0;
    increment(&a);
    cout << "Value of a in main function : " << a << endl;
    return 0;
}
                           
                       

output ↓

                           
Value of a in increment function : 1
Value of a in main function : 1
                           
                       
                                                     
#include <iostream>
using namespace std;
void swap(int *x, int *y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}
int main()
{
    int a = 5, b = 10;
    cout << "Value of a and b before swap : a = " << a << ", b = " << b << endl;
    swap(&a, &b);
    cout << "Value of a and b after swap : a = " << a << ", b = " << b << endl;
    return 0;
}
                           
                       

output ↓

                        

Value of a and b before swap : a = 5, b = 10
Value of a and b after swap : a = 10, b = 5
                        
                       

Recursion

Example program of factorial using recursion ↓

                   
#include <iostream>
using namespace std;

int factorial(int);

int main()
{
    int n = 4, result;
    result = factorial(n);
    cout << "Factorial of " << n << " = " << result;
    return 0;
}

int factorial(int n)
{
    if(n > 1)
    {
        return n * factorial(n - 1);
    } else {
        return 1;
    }
}
                   
               

Output ↓

                    
Factorial of 4 = 24
                   
               

C++ Structures

Structure syntax

  • The 'struct' keyword is used to create a structure.
                                       
struct structureName{
    member1;
    member2;
    member3;
    .
    . 
    . 
    memberN;
}
                       
                   

Structure variable declaration

  • A structure variable can either be declared with structure declaration or as a separate declaration like basic types.
                       
// A variable declaration with structure declaration. 
struct Point
{
    int x, y;
} p1;  // The variable p1 is declared with 'Point'
                       
                   
                                          
// A variable declaration like basic data types
struct Point
{
    int x, y;
};

int main()
{
    struct Point p1; // The variable p1 is declaraed like a normal variable
}
                       
                   

Initializing structure member

  • Structure members cannot be initialized with declaration.
  • For example the following C program fails in compilation. But is considered correct in C++11 and above.
                                           
struct Point
{
    int x = 0; // COMPILER ERROR:  cannot initialize members here
    int y = 0; // COMPILER ERROR:  cannot initialize members here
}
                       
                   
  • The reason for above error is simiple, when a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created.
  • We use dot (.) operator to intialize value and access member variable.
  • Structure members can be initialized with declaration in C++. For example the following C++ program executes successfully without throwing any Error.
                                             
// In C++ We can Initialize the Variables with Declaration in Structure.
#include <iostream>
using namespace std;
struct Point
{
    int x = 0; // It is considered as Default Arguments and no Error is Raised.
    int y = 1;
};
int main()
{
    struct Point p1;

    // Accessing members of point p1
    // No value is Initialized then the default value is considered. ie x = 0 and y = 1
    cout << "x = " << p1.x << ", y = " << p1.y << endl;

    // Initializing the value of y = 20;
    p1.y = 20;
    cout << "x = " << p1.x << ", y = " << p1.y << endl;
    return 0;
}
                       
                   

Output ↓

                                      
x=0, y=1
x=0, y=20
                       
                   
  • Structure members can be initialized using curly braces '{}'.
                                              
struct Point
{
    int x, y;
};

int main()
{
    struct Point p1 = { 0, 1};
    return 0;
}
                       
                   

Array of structure

  • Like other primitive data types, we can create an array of structures.
                                             
#include <iostream>
using namespace std;

struct Point
{
    int x, y;
};

int main()
{
    // Create an array of structures
    struct Point arr[10];

    // Access array members
    arr[0].x = 10;
    arr[0].y = 20;

    cout << arr[0].x << " " << arr[0].y;
    return 0;
}
                       
                   

References