C++ Constructor
In C++, constructor is a special method which is invoked automatically at the time of object
creation.
It is used to initialize the data members of new object generally.
The constructor in C++ has the same name as class or structure.
class Wall {
public:
// create a constructor
Wall() {
// code
}
};
Constructor vs Member function
1) Constructor doesn’t have a return type. Member function has a return type.
2) Constructor is automatically called when we create the object of the class. Member function
needs to be called explicitly using object of class.
3) When we do not create any constructor in our class, C++ compiler generates a default
constructor and insert it into our code. The same does not apply to member functions.
Properties of Constructor in C++
The name of the constructor should be the same as that of the class.
A constructor should not have any return type.
A constructor is automatically invoked as soon as we create an object.
A constructor is associated with the class.
A constructor may have default parameters or arguments.
We cannot use the const keyword along with the constructor name, although C++ allows the constructor
to be invoked for an object of constant value.
A constructor does not have the provision to refer to its own address.
Definition inside the class
class Class_name class A
{ {
public: public:
int variable; int variable;
class_name() // Defining a constructor A() // Defining a constructor
{ {
variable = 0; // Initialzing the object to 0
variable = 0; // Initialzing the object to 0
}
}
};
};
int main()
int main()
{
{
A c; // Creation of an object
Class_name c; // Creation of an object
return 0;
return 0;
}
}
Definition outside the class
Syntax
class class_name {
public:
//Constructor declaration
class_name();
//... other Variables & Functions
};
// Constructor definition outside Class
class_name::class_name() {
// Constructor code
}
Example
Types of Constructor
Default Constructor
Default constructor does not have any parameter.
This type of constructor is important for initialization of object members.
Syntax:
class_name()
{
//Constructor Definition
}
Demonstrating the Default Constructor
#include<iostream>
using namespace std;
class Rectangle
{
public:
float l,b;
Rectangle() //Constructor created
{
l=3; Output:
Area of Rectangle : 18
b=6;
}
Demonstrating how the default constructor is
called by the compiler
#include<iostream>
using namespace std;
class Rectangle
Output:
{ Area of Rectangle : 9
public: int l=3,b=3;
};
int main()
{
Rectangle rect;
cout<<"Area of Rectangle : "<<rect.l*rect.b;
}
Parameterized Constructor
Parameterized Constructor is defined with the parameters which provide different values to data
members of different objects by passing the values as an argument.
Example
#include <iostream>
using namespace std;
class Employee {
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
public:
Employee(int i, string n, float s)
{
id = i;
name = n;
Cont..
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
[Link]();
[Link]();
return 0;
}
Copy Constructor
Copy Constructors is a type of constructor which is used to create a copy of an already existing
object of a class type. It is usually of the form X (X&), where X is the class name.
The compiler provides a default Copy Constructor to all the classes.
Syntax:
class_name (const class_name &obj)
{
//body of constructor;
}
Program demonstrating the Copy
Constructor
#include<iostream>
using namespace std;
class sample
{
private:
int x, y; //data members
public:
sample(int x1, int y1)
{
x = x1;
Cont..
void display()
{
cout<<x<<" "<<y<<endl;
}
};
/* main function */
int main()
{
sample obj1(10, 15); // Normal constructor
sample obj2 = obj1; // Copy constructor
sample obj3(obj2);
Output:
num1 = 10
num2 = 20
num1 = 10
num2 = 20
Constructor overloading in C++
The use of multiple constructors in the same class is known as constructor overloading. The
constructor must follow one or both of the two rules below.
All the constructors in the class should have a different number of parameters.
It is also allowed in a class to have constructors with the same number of parameters and different
data types.
Examples of Legal and Illegal Constructor
Overloading
Here are some examples of legal and illegal constructor overloading:
❑Addition(int x, int y) and Addition(double x, double y) is legal in constructor overloading.
❑Addition(int x, int y) and Addition(int x, double y) is legal in constructor overloading.
❑Addition(int x, int y) and Addition(int x, int y) is illegal in constructor overloading.
❑Addition(double x, double y) and Addition(double x, double y) is illegal in constructor
overloading.
Declaration of Constructor Overloading in
C++
class ClassName {
public:
ClassName() {
body; // Constructor with no parameter.
}
ClassName(int x, int y) {
body; // Constructor with two parameters.
}
ClassName(int x, int y, int z) {
body; // Constructor with three parameters.
}
ClassName(ClassName & object) {
body; // Constructor with the same class object as a parameter.
}
// Other member functions.
};
// C++ program to demonstrate constructor
overloading
#include <iostream>
using namespace std;
class Area {
private:
// Member Variable Declaration.
int area;
public:
// This is a Constructor with no parameters.
Area() {
area = 0;
Cont..
// This is a Constructor with two parameters.
Area(int length, int width) {
area = length * width;
}
// Member function declaration.
int disp() {
return area;
}
}; int main() { Output:
Area point; Area of point: 0
Area of square: 25
Area square(5); Area of rectangle: 54
Area rectangle(6, 9);
cout << "Area of point: " << [Link]() << endl;
Destructor in C++
Destructor is a member function which deletes an object.
A destructor is called automatically by the compiler when the object goes out of scope.
A destructor is a special member function that works just opposite to constructor, unlike
constructors that are used for initializing an object, destructors destroy (or delete) the object.
A destructor works opposite to constructor and defined like constructor; it destructs the objects of
classes.
It can be defined only once in a class and must have same name as class.
Like constructors, it is invoked automatically. But it is prefixed with a tilde sign (~).
Syntax:
class class_name
{
public:
~class_name();
};
Properties of Destructor
A constructor is different from normal functions in following ways:
Destructor function is automatically invoked when the objects are destroyed.
It cannot be declared static or const.
The destructor does not have arguments.
It has no return type not even void.
An object of a class with a Destructor cannot become a member of the union.
A destructor should be declared in the public section of the class.
The programmer cannot access the address of destructor.
When does the destructor get called?
A destructor function is called automatically when the object goes out of scope:
(1) When the function ends.
(2) When the program ends.
(3) When a scope (the { } parenthesis) containing local variable ends.
(4) When a delete operator is called.
Demonstrating the
Destructor-Example 1
#include <iostream>
using namespace std;
// declare a class
class hello {
public:
// Constructor
hello() {
cout << "Constructor is Called." << endl;
}
// Destructor
~hello() {
Cont..
// Member Function
int display(){
cout << "Hello, Programmer." << endl;
}
};
int main() { Output
// create an object Constructor is Called.
Hello, Programmer.
hello obj1; Destructor is Called.
// Member function called
[Link]();
Demonstrating the Destructor-Example 2
#include <iostream>
using namespace std;
int count=0;
class show
{
public:
show()
{
count++;
cout << "Create Object : " << count<<endl;
}
Cont..
int main()
{
cout << "Main Objects: a,b,c\n";
show a,b,c;
{
cout << "\n New object: d\n";
show d;
}
cout << "\n Destroy All objects: a,b,c\n";
return 0;
}
Output:
Main Objects: a,b,c
Create Object : 1
Create Object : 2
Create Object : 3
New object: d
Create Object : 4
Destroyed Object : 4
Destroy All objects: a,b,c
Destroyed Object : 3
INHERITANCE
Inheritance
❑The capability of a class to derive properties and characteristics from another class is called
Inheritance.
❑ Inheritance is one of the most important feature of Object Oriented Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or Super
class.
❑To inherit from a class, use the : symbol.
Why and when to use inheritance?
Solution
Implementing inheritance in C++:
Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Example
class Parent
{
public:
int id_p;
};
Output:
class Child : public Parent
Child id is 7
{
Parent id is 91
public:
int id_c;
};
//main function
Modes of Inheritance
❑Public mode: If we derive a sub class from a public base class. Then the public member of the
base class will become public in the derived class and protected members of the base class will
become protected in derived class.
❑Protected mode: If we derive a sub class from a Protected base class. Then both public member
and protected members of the base class will become protected in derived class.
❑Private mode: If we derive a sub class from a Private base class. Then both public member and
protected members of the base class will become Private in derived class.
class A
{
public:
Example
int x;
protected:
int y;
private:
int z;
};
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
Types of Inheritance
Single Inheritance
Syntax
class base_class
{
//code
};
class derived_class : public(access_modifier) base_class
{
//code
};
int main()
{
base_class object_1;
Example 1
#include <iostream> class Derived : public Base
{
using namespace std;
// private by default
class Base int derived_value;
{ public:
void derived_input()
public:
{
int base_value; cout<<"Enter the integer value of derived class: ";
void base_input() cin>>derived_value;
{ }
void sum()
cout<<"Enter the integer value of base class: "; {
cin>>base_value; cout << "The sum of the two integer values is: " <<
} base_value + derived_value<<endl;
}
};
};
Cont..
int main()
{
Derived d; // Object of the derived class
d.base_input();
d.derived_input();
[Link]();
return 0;
}
Multiple Inheritance
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
//body of subclass
};
class Vehicle {
public:
Vehicle()
{
Example
cout << "This is a Vehicle" << endl;
}
};
// second base class
class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle" << endl;
}
};
Output:
This is a Vehicle
This is a 4 wheeler Vehicle
// sub class derived from two base classes
Multilevel Inheritance in C++
Syntax
class A // Base class
{
// BODY OF CLASS A
};
class B : acess_specifier A // Derived class of A
{
// BODY OF CLASS B
};
class C : access_specifier B // Derived from derived class B
{
// BODY OF CLASS C
};
Example
#include <iostream>
class Derived1 : public Base // Derived class of base class
using namespace std; {
public:
class Base
int derived1_value;
{ void Derived1_input()
public: {
cout<<"Enter the integer value of first derived class: ";
int base_value; cin>>derived1_value;
void Base_input() }
};
{
cout<<"Enter the integer value of base class: ";
cin>>base_value;
}
class Derived2 : public Derived1 // Derived class of Derived1 class
{
// private by deafult
int derived2_value;
public:
void Derived2_input()
{
cout<<"Enter the integer value of the second derived class: ";
cin>>derived2_value;
}
void sum()
int main()
{
Derived2 d2; // Object d2 of second derived class
d2.Base_input();
d2.Derived1_input();
d2.Derived2_input();
[Link]();
return 0;
}
Hierarchical Inheritance
Syntax
class base_classname
{
properties;
methods;
};
class derived_class1:visibility_mode base_classname
{
properties;
methods;
};
class derived_class2:visibility_mode base_classname
Example
#include <iostream>
using namespace std;
class Side
{
protected:
int l;
public:
void set_values (int x)
{ l=x;}
Output
}; Total Objects: 1
The square value is:: 100
class Square: public Side
The cube value is::8000
{
C++ Hybrid Inheritance
Syntax
class A
{
.........
};
class B : public A
{
..........
};
class C
{
...........
Example
#include <iostream>
using namespace std;
class A
{
public:
int x;
};
class B : public A
{
public:
B() //constructor to initialize x in base class A
Cont..
class D : public B, public C
{
public:
void sum()
{
cout << "Sum= " << x + y;
} Output
}; Sum= 14
int main()
{
Example -2
#include<iostream>
#include<conio>
using namespace std;
class arithmetic
{
protected:
int num1, num2;
public:
void getdata()
{
cout<<"For Addition:";
Cont..
class plus:public arithmetic
{
protected:
int sum;
public:
void add()
{
sum=num1+num2;
}
};
class minus
Cont..
class result:public plus, public minus Output:
{
For Addition
public:
Enter the first number:10
void display() Enter the second number:5
{
For Subtraction:
cout<<"\nSum of "<<num1<<" and "<<num2<<"= "<<sum;
Enter the first number:10
cout<<"\nDifference of "<<n1<<" and "<<n2<<"= "<<diff; Enter the second number:5
}
Sum of 10 and 5= 15
}; Difference of 10 and 5= 5
int main()
{
Assignment
1) Analyze the below the figure and find what type of inheritance and implement the code using
c++.