0% found this document useful (0 votes)
6 views

Constructor, destructors and inheritance

The document provides an overview of classes and objects in C++, detailing their definitions, attributes, and methods. It explains concepts such as the 'this' pointer, access modifiers, inheritance types, constructors, destructors, data abstraction, encapsulation, and overloading. Additionally, it covers memory allocation for objects, static members, and the order of constructor/destructor calls in derived classes.

Uploaded by

Aryaman Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Constructor, destructors and inheritance

The document provides an overview of classes and objects in C++, detailing their definitions, attributes, and methods. It explains concepts such as the 'this' pointer, access modifiers, inheritance types, constructors, destructors, data abstraction, encapsulation, and overloading. Additionally, it covers memory allocation for objects, static members, and the order of constructor/destructor calls in derived classes.

Uploaded by

Aryaman Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Class and objects

• A class is a user defined data type which works as an object constructor or a blueprint for
creating objects.

• The members of a class are attributes and methods.

• class class_name{ class class_name{

access_specifier: access_specifier;
data members; data members;
ReturnType function(){ // body} ReturnType function(); };

}; ReturnType class_name :: function(){


//body
}
// Defining member function outside the class
Class and objects

• Object is an instance of a class that encapsulates data and functionality pertaining


to that data.

• Objects and classes are used to wrap related functions and data in one place in
c++.

• classname objectname;
This pointer
• The 'this' pointer contains the address of the current object and makes it easy for
member function to access the data members. It allows objects to refer to
themselves within their own scope.

• Every object in C++ has access to its own address through “this” pointer. It is
passed as a hidden argument to all non-static member function calls. Static
member functions don’t have a “this” pointer.

• This pointer can also be used to access the data members inside the member
function. It can be done with the help of arrow operator (− >).

void memberfunction(){
this->memberName = value;
}
Access modifier

• Public: Members of a class are accessible from anywhere in the program.

• Private: Members can only be accessed from within the class

• Protected: Members can be accessed within the class and from the derived class
Derived class

• It is a class that is constructed from a base class.


• It inherits all the methods and properties of base class.
• It will have its own instance variables and member functions.

• class derived_classname: access_mode base_class_name


{
// Data members ...
// Member functions ....

}
Visibility of inherited members

Base class Derived class

Public Private Protected


Private Not inherited Not inherited Not inherited
Protected Protected Private Protected
Public Public Private Protected

• When deriving a class from a base class, the base class may be inherited through
public, private or protected inheritance.
• The type of inheritance is specified by the access-specifier.
Visibility of inherited members

• Public Inheritance: The public members of the base class become public
members of the derived class and protected members of base class become
protected members of derived class. A base class’s private members are never
accessible directly from a derived class. But can be accessed through calls to
public and protected members of the class.

• Protected Inheritance: When deriving from a protected base class, public and
protected members of the base class become protected members of the derived
class.

• Private Inheritance: When deriving from a private base class, all members of
base class become private members of the derived class.
Static Data Members
• A static member is shared by all objects of a class.

• When the first object is created all static members are initialized to zero provided
there is no other initialization.

• The static member has to be initialized outside the class and before main function
using the scope resolution operator.

Datatype classname::static_variable;

• When we declare a member as static, it means that there is only one copy of the
static member irrespective of the number of objects of the class.
Static Member Functions

• A static member function can only access static data members, other static member
functions, and any other functions from outside the class.

• Static member functions are not associated with a particular object, they can be
called directly by using the class name and the scope resolution operator.

• Can be called using the class name (even if no objects of the class exist) as follows-

classname::static_function_name();
Objects Memory Allocation & Array of Objects

• Although the variables and functions are from same class memory is allocated in
a different way.

• The memory is not allocated to the variables when the class is declared. In every
object each variable can have different values for different objects. So, every
object will have an individual copy of all the variables of the class.

• The memory is allocated only once to the member function when the class is
declared. So the objects will not have an individual copy of the functions, but one
copy is shared among each object.
Display() Static member

Obj1 (name, age, height) Obj2 (name, age, height)

• Object is placed in a stack in contiguous blocks of memory.


• The size of memory to be allocated is known to the compiler.
• The stack has fixed size (OS-dependent).
• The compiler automatically allocate/deallocate the memory to avoid stack
overflow.
• Heaps are used for allocating memory for dynamically created objects.
Constructors

• Constructor:
(1) Special member function of a class which initializes the objects of a class in C++.
(2) Has same name as the class, but donot have a return type.
(3) Compiler automatically generates a default constructor (no parameters and no
body) when an object is created.

Types of constructors -> (1) Default, (2) Parameterized, and (3) Copy constructor
Default constructors
• Default constructor is the constructor which doesn’t take any argument. It is a
special member function that has same name as the class and takes no
parameters.
• Even if we do not define any constructor explicitly, the compiler will automatically
provide a default constructor.

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.
Copy constructors
• Copy Constructor is a type of constructor which is used to create a copy of an
already existing object of a class type.

• A copy constructor is a member function which initializes an object using another


object of the same class.

• There are default and user-defined copy constructors. The user-defined copy
constructor in C++ is specifically needed when the class has one or more data
members that are pointers or references.
Role of Constructor
• It is called by the compiler whenever an object of the class if created.

• It allocates the memory to the object and initializes the data members by
default values or values passed by the user while creating the object.

• They don’t have return type, because their purpose is only to create and
initialize the object.

• A derived class contains all members and functions(including constructors)


of the base class.

• Constructors of superclass cannot be inherited by subclasses, but they can


be invoked from the subclass.
Destructors
(1) Destructs or deletes an object.

(2) Have same name as class but preceded by a tilde (~). Does not take any argument
and don’t return anything (not even void)

(3) It is called when the object goes out of scope such as function ends or program
ends or a delete operator is called.

(4) There can be only one destructor in a class. If we do not write our own destructor in
class, compiler creates a default destructor for us.

(5) The default destructor works fine unless we have dynamically allocated memory or
pointer in class. When a class contains a pointer to memory allocated in class, we
should write a destructor to release memory before the class instance is destroyed.
Data Abstraction
Abstraction refers to the act of representing essential features without including background
details or explanations to the user.

The main purpose is to expose only the essential elements of a device. For example, one can
figure out how to change the TV channels using remote but cannot tell how the channels are
getting changed when the buttons of the remote are pressed.

Data Encapsulation
The wrapping up of data and function into a single unit is known as encapsulation.
The data is not accessible to the outside world and only those functions which are
wrapped in the class can access it. These functions provide the interface between
the object’s data and the program.

Abstraction – information hiding , Encapsulation – Data hiding


Overloading

Function overloading :
• Two or more function with the same name, but different in parameters is known as
function overloading in C++.
• The function is redefined by using either different types of arguments or a different
number of arguments. It is only through these differences' compiler can differentiate
between the functions.

void display(int p, int c)


{ ... .. ... }

void display(int p, float c)


{ ... .. ... } // overloaded function
Overloading
Operator overloading:
Operator overloading is a feature in C++ that allows operators such as +, -, *, /, =, and many others to
be redefined for user-defined types like classes.

returnType operator symbol (arguments)


{ ... .. ... }

Operators that cannot be overloaded :

-> Scope operator (::)


-> Sizeof
-> member selector(.)
-> member pointer selector(*)
-> ternary operator(?:)
Destructors

(1) Destructs or deletes an object.


(2) Have same name as class but preceded by a tilde (~). Does not take any
argument and don’t return anything (not even void)
(3) It is called when the function ends or program ends.
(4) There can be only one destructor in a class. If we do not write our own
destructor in class, compiler creates a default destructor for us.
(5) The default destructor works fine unless we have dynamically allocated memory
or pointer in class.
Order of constructor/Destructor call in c++ - Derived class

• When there is a derived class, data members and functions comes automatically in
derived class based on the access specifier, but the definition exists only in the base
class.

• When an object is created all of the members of derived class should be initialized but
for the inherited members initialization can be done only by the base class’s constructors
as their definition exists only in the base class.

• Therefore, constructor of base class is called first to initialize all the inherited members.

-> Always base class constructor is called first followed by a derived class constructor.
-> Derived class destructor is executed first, followed by the base class destructor.
Array of objects
• It represent storing multiple objects in a single name.
• Data can be accessed using the index number.
• Classname object[number of objects]

roll_no cgpa
Stud[0]
Stud[1]
Stud[2]
Array of objects
• Declaring array of objects

classname obj[N]; // N is the number of objects to be created


classname obj[N] = {classname(values for data members), ….}
// initializing array of objects

classname* obj = new classname[N]; // allocating dynamic array

Whenever dynamic allocation is there, the objects will be stored in HEAP and it is
required to implicitly invoke the destructor to destroy the objects when they go out
of scope.
Inheritance
• In C++, inheritance is a process in which one object acquires all the properties
and behaviors of its parent object automatically. In such way, you can reuse,
extend or modify the attributes and behaviors which are defined in other class.

• In C++, the class which inherits the members of another class is called derived
class and the class whose members are inherited is called base class. The derived
class is the specialized class for the base class.
Advantages of C++ inheritance

Code reusability: Now you can reuse the members of your parent class. So, there is
no need to define the member again. So less code is required in the class.

Types Of Inheritance: C++ supports five types of inheritance:

• Single inheritance
• Multiple inheritance
• Hierarchical inheritance
• Multilevel inheritance
• Hybrid inheritance
Single Inheritance
• Single inheritance is defined as the inheritance in which a derived class is inherited
from the only one base class.

• Public and Protected Access specifier for base class allows derived classes to use base
class members.

• Private Access specifier will not allow derived class to inherit base class members.

class A // base class { ........... };

class B : access_specifier A // derived class { ........... } ;


Multi-level Inheritance
• When one class inherits another class which is further inherited by another
class, it is known as multi level inheritance in C++.

• In heritance is transitive so the last derived class acquires all the members of
all its base class.

class A // base class { ........... };

class B : access_specifier A // derived class { ........... } ;

class C : access_specifier B // derived from derived class B { ........... } ;


Multiple Inheritance
• A class can inherit from more than one classes. i.e one sub class is
inherited from more than one base classes.

class A
{
... .. ...
};

class B // Here A and B are base classes


{
... .. ... // C is the derived class
};

class C: public A,public B


{
... ... ...
};
Hierarchical Inheritance
• Hierarchical inheritance is defined as the process of deriving more than one
class from a base class.

Class A { ............ }; // A is the base class

Class B: access_specifier A { ......... }; // B and C are the derived classes

Class C: access_specifier A { ............. };

Hybrid Inheritance

• Hybrid Inheritance is implemented by combining more than one type of


inheritance. For example: Combining Hierarchical inheritance and Multiple
Inheritance.

You might also like