100% found this document useful (1 vote)
692 views

Introduction To C++-Module3-BPLCK105D-205D

The document discusses different types of constructors in C++ including default, parameterized, copy, overloaded and inline constructors. It provides examples and definitions of each type of constructor and their key characteristics.

Uploaded by

Mohammed owais
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
692 views

Introduction To C++-Module3-BPLCK105D-205D

The document discusses different types of constructors in C++ including default, parameterized, copy, overloaded and inline constructors. It provides examples and definitions of each type of constructor and their key characteristics.

Uploaded by

Mohammed owais
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Module 3

Constructor:-
1. Define Constructor with syntax, explain with an example?
Defn:- Constructor in C++ is a special method that is invoked automatically at the time of object
creation. It is used to initialize the data members of new objects generally.
o The constructor in C++ has the same name as the class or structure.
o Constructor is invoked at the time of object creation.
o Constructor is a member function of a class, whose name is same as the class name.
o Constructor is a special type of member function that is used to initialize the data members
for an object of a class automatically, when an object of the same class is created.
o Constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.
o Constructor do not return value, hence they do not have a return type.

The prototype of the constructor looks like


<class-name> (list-of-parameters);
Constructor can be defined inside the class declaration or outside the class declaration
a. Syntax for defining the constructor within the class
<class-name>(list-of-parameters)
{
//constructor definition
}
b. Syntax for defining the constructor outside the class
<class-name>: :<class-name>(list-of-parameters)
{
//constructor definition
}

Example:-- 1
// Example: defining the constructor within the class
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 1


student()
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}
void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
};
int main()
{
student s; //constructor gets called automatically when we create the object of the class
s.display();
return 0;
}

Example:-- 2
// Example: defining the constructor outside the class
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student();
void display();
};
student::student()
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}
void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
int main()

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 2


{
student s;
s.display();
return 0;
}

2. What are the characteristics of the Constructor?


Characteristics of Constructors
 The name of the constructor is the same as its class name.
 Constructors are mostly declared in the public section of the class though it can be declared in
the private section of the class.
 Constructors do not return values; hence they do not have a return type.
 A constructor gets called automatically when we create the object of the class.
 Constructors can be overloaded.
 Constructor can not be declared virtual.
 Constructor cannot be inherited.
 Addresses of Constructor cannot be referred.
 Constructor make implicit calls to new and delete operators during memory allocation.

3. Mention the types of Constructor


Types of constructor
• Default constructor
• Parameterized constructor
• Overloaded constructor
• Constructor with default value
• Copy constructor
• Inline constructor

4. Demonstrate the all 5 types of constructor with an example?


1. Default Constructors:
Default constructor is the constructor which doesn’t take any argument. It has no
parameters. It is also called a zero-argument constructor.

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 3


Example 1:
#include <iostream>
using namespace std;
class construct {
public:
int a, b;
construct() // Default Constructor
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
}
OutPut: a: 10
b: 20

Example 2:
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student() // Explicit Default constructor
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}
void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
};
int main()
{
student s;

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 4


s.display();
return 0;
}

2. Parameterized Constructors:

It is possible to pass arguments to constructors. Typically, these arguments help initialize an


object when it is created. To create a parameterized constructor, simply add parameters to it the way
you would to any other function. When you define the constructor’s body, use the parameters to
initialize the object.
Example1:
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();
return 0;
}
Output:-
p1.x = 10, p1.y = 15.

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 5


Uses of Parameterized constructor:
 It is used to initialize the various data elements of different objects with different values when
they are created.
 It is used to overload constructors.

3. Copy Constructor:
A copy constructor is a member function that initializes an object using another object of the
same class. A detailed article on Copy Constructor.
Whenever we define one or more non-default constructors( with parameters ) for a class, a
default constructor( without parameters ) should also be explicitly defined as the compiler will not
provide a default constructor in this case. However, it is not necessary but it’s considered to be the
best practice to always define a default constructor.
Copy constructor takes a reference to an object of the same class as an argument.

Example 1:
#include<iostream.h>
using namespace std;
class Sample
{
int id;
public:
void init(int x)
{
id=x;
}
Sample(){} //default constructor with empty body

Sample(Sample &t) //copy constructor


{
id=t.id;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 6


Sample obj2(obj1); //or obj2=obj1; copy constructor called
obj2.display();
return 0;
}
Output
ID=10
ID=10

4. Constructor Overloading:
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.
 Addition(int x, int y) and Addition(int x, int y, int z) is legal in constructor overloading.
Example: Structure of OverLoading
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.
}};
Example 2:
// C++ program to demonstrate constructor overloading.
#include <iostream>
using namespace std;
class Area {

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 7


public:
int area;
. Area() // Constructor with no arguments
{
area = 0;
}
Area(int side) // Constructor with one argument.
{
area = side * side;
}
Area(int length, int width) // Constructor with two arguments.
{
area = length * width;
}
int disp()
{
return area;
}
};
int main() {
Area obj1;
Area obj2(6);
Area obj3(8, 5);
cout << "Area of obj1: " << obj1.disp() << endl;
cout << "Area of obj2: " << obj2.disp() << endl;
cout << "Area of obj3: " << obj3.disp() << endl;
return 0;
}
Output
Area of obj1: 0
Area of obj2: 36
Area of obj3: 40

5. Constructors with Default Arguments in C++:

Default arguments of the constructor are those which are provided in the constructor
declaration. If the values are not provided when calling the constructor the constructor uses the
default arguments automatically.
Example:
#include<iostream>
using namespace std;
class Simple{
int data1;
int data2;
int data3;

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 8


public:
Simple(int a, int b=9, int c=8){
data1 = a;
data2 = b;
data3 = c;
}
void printData();
};
void Simple :: printData(){
cout<<"The value of data1, data2 and data3 is "<<data1<<", "<< data2<<" and "<<
data3<<endl;
}
int main(){
Simple s(12, 13);
s.printData();
return 0;
}
Output:
The value of data1, data2 and data3 is 12,13,8.

Explanation of code:
 1st we created a “simple” class which consists of private data members “data1”, “data2” and
“data3”.
 2nd parameterized constructor of the “simple” class is defined which takes three parameters
and assigns values to the data members “a” and “b”. The main thing to note here is that the
value “9” and “8” are the default values for the variables “b” and “c”.
 3rd function “printData” is defined which prints the values of the data members “data1”,
“data2”, and “data3”.
 4th parameterized constructor is called with the object “s” of the data type “simple” and the
values “12” and “13” are passed.
 The main thing to note here is that the value of the parameter “c” will be automatically set by
the default value.
 2nd function “printData” is called which will print the values of data members.

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 9


6. Mention the difference between the Constructor and the Methods

7. Define Destructor with syntax and explain with an example?

Destructor:-
Defn:- A destructor is also a special member function as a constructor. Destructor destroys the
class objects created by the constructor.
Destructor has the same name as their class name preceded by a tilde (~) symbol.
The syntax for defining the destructor within the class
~ <class-name>()
{
}
The syntax for defining the destructor outside the class
<class-name>: : ~ <class-name>(){}
 Destructor has the same name as their class name preceded by a tilde (~) symbol.
 It is not possible to define more than one destructor.
 The destructor is only one way to destroy the object created by the constructor. Hence destructor
can-not be overloaded.
 Destructor neither requires any argument nor returns any value. It is automatically called when
the object goes out of scope.

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 10


 Destructors release memory space occupied by the objects created by the constructor. In
destructor, objects are destroyed in the reverse of object creation.

8. Demonstrate the destruction of an object in the class with an example

Example1:-
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "\n Constructor executed"; }

~Test() { cout << "\n Destructor executed"; }


};
main()
{
Test t;
return 0;
}
Output
Constructor executed
Destructor executed

Example2:-
#include <iostream>
using namespace std;
int count = 0;
class Test {
public:
Test()
{
count++;
cout << "\n No. of Object created:\t" << count;
}

~Test()
{
cout << "\n No. of Object destroyed:\t" << count;
--count;
}
};
main()
{
Test t, t1, t2, t3;
return 0;
}

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 11


Output
No. of Object created: 1
No. of Object created: 2
No. of Object created: 3
No. of Object created: 4
No. of Object destroyed: 4
No. of Object destroyed: 3
No. of Object destroyed: 2
No. of Object destroyed: 1

9. Mention the Properties of Destructor:-

Properties of Destructor:-
1. Destructor is invoked automatically by the compiler when its corresponding constructor goes out
of scope and releases the memory space that is no longer required by the program.
2. Destructor neither requires any argument nor returns any value therefore it cannot be overloaded.
3. Destructor cannot be declared as static and const;
4. Destructor should be declared in the public section of the program.
5. Destructor is called in the reverse order of its constructor invocation.

10. Define inheritance with syntax and demonstrate with example?


Define Inheritance in C++ with an Example?

Inheritance:
Defn:- The capability of a class to derive properties and characteristics from another class is called
Inheritance.
 Inheritance is one of the most important features of Object-Oriented Programming.
 Inheritance is a feature or a process in which, new classes are created from the existing classes.
The new class created is called “derived class” or “child class” and the existing class is known as
the “base class” or “parent class”. The derived class now is said to be inherited from the base
class.
 When we say derived class inherits the base class, it means, the derived class inherits all the
properties of the base class, without changing the properties of base class and may add new
features to its own. These new features in the derived class will not affect the base class. The
derived class is the specialized class for the base class.

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 12


Sub Class: The class that inherits properties from another class is called Subclass or Derived
Class.
Super Class: The class whose properties are inherited by a subclass is called Base Class or
Superclass.

11. Mention the derived classes in inheritance?


Derived Classes: A Derived class is defined as the class derived from the base class.
Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
}
Where
 class — keyword to create a new class
 derived_class_name — name of the new class, which will inherit the base class
 access-specifier — either of private, public or protected. If neither is specified, PRIVATE is
taken as default
 base-class-name — name of the base class
Modes of Inheritance: There are 3 modes of inheritance.
 Public Mode: If we derive a subclass 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 the derived class.
 Protected Mode: If we derive a subclass from a Protected base class. Then both public members
and protected members of the base class will become protected in the derived class.
 Private Mode: If we derive a subclass from a Private base class. Then both public members and
protected members of the base class will become Private in the derived class.

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 13


Example:-

class A {
public:
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
};
class D : private A // 'private' is default for classes
{
// x is private
// y is private
// z is not accessible from D
};

12. Mention the Types of Inheritance ?

Types of Inheritance:-

 Single inheritance
 Multilevel inheritance
 Multiple inheritance
 Hierarchical inheritance
 Hybrid inheritance

13. Expalin each of the inheritance with an example?

1. Single Inheritance:
In single inheritance, a class is allowed to inherit from only one class. i.e. one subclass is inherited by
one base class only.

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 14


Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};
OR
class A
{
... .. ...
};
class B: public A
{
... .. ...
};
Example:
// C++ program to explain
// Single inheritance
#include<iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

// sub class derived from a single base classes


class Car : public Vehicle {

};

// main function

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 15


int main()
{
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output
This is a VehicleExample:-

2. Multiple Inheritance:
Multiple Inheritance is a feature of C++ where a class can inherit from more than one class. i.e one
subclass is inherited from more than one base class.

Syntax:

class subclass_name : access_mode base_class1, access_mode base_class2, ....


{
// body of subclass
};
class B
{
... .. ...
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ... };

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 16


Example:-
C++ program to explain
// multiple inheritance
#include <iostream>
using namespace std;

// first base class


class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// second base class


class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle\n";
}
};

// sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}
Output
This is a Vehicle
This is a 4 wheeler Vehicle

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 17


3. Multilevel Inheritance:
In this type of inheritance, a derived class is created from another derived class.

Syntax:-

class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};

Example:-
C++ program to implement
// Multilevel Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub_class derived from class vehicle


class fourWheeler : public Vehicle {
public:
fourWheeler()

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 18


{
cout << "Objects with 4 wheels are vehicles\n";
}
};
// sub class derived from the derived base class fourWheeler
class Car : public fourWheeler {
public:
Car() { cout << "Car has 4 Wheels\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}
Output
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels

4. Hierarchical Inheritance:
In this type of inheritance, more than one subclass is inherited from a single base class. i.e. more than
one derived class is created from a single base class.

Syntax:-
class A
{
// body of the class A.
}
class B : public A

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 19


{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}

Example:-
// C++ program to implement
// Hierarchical Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
};

// second sub class


class Bus : public Vehicle {
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Car obj1;
Bus obj2;
return 0;
}
Output
This is a Vehicle
This is a Vehicle

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 20


5. Hybrid (Virtual) Inheritance:
Hybrid Inheritance is implemented by combining more than one type of inheritance.
For example: Combining Hierarchical inheritance and Multiple Inheritance.

Below image shows the combination of hierarchical and multiple inheritances:

Example:-
C++ program for Hybrid Inheritance

#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
// base class
class A{
public:
Fare() { cout << "In A Class\n"; }
};
// first sub class
class Car : public Vehicle {
};
// second sub class
class Bus : public Vehicle, public A {
};
// main function
int main()
{

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 21


// Creating object of sub class will
// invoke the constructor of base class.
Bus obj2;
return 0;
}

Output
This is a Vehicle
In A Class.

GMIT,AIML Dept. Introduction to C++ (BPLCK105D) Page 22

You might also like