My Blog
Articles related to programming, computer science, technology and research.

27/09/2016 Categories: C++ Programming. No Comments on Constructors and Destructors in C++

Introduction

 

Until now in our C++ programs, we are initializing the data members of a class by creating one or more member functions and passing values as parameters to those functions. We know that C++ considers user-defined types on par with pre-defined types. We can initialize a pre-defined type at the time of declaration itself as shown below:

 

int x = 20;

 

Similarly, to initialize the data members when an object is created, C++ provides a special member function called a constructor and to de-initialize an object, another special member function called a destructor is used.

 

Constructor

 

Constructor is a special member function which is invoked automatically when an object is created to initialize the data members of that object. Following are the characteristics of a constructor:

  • The name of a constructor is same as the class name.
  • A constructor must be declared in public section of the class.
  • It should not be called explicitly as it is automatically called when an object is created.
  • A constructor doesn’t return any value. So, a constructor doesn’t have any return type. Not even void.
  • A constructor cannot be inherited or virtual.
  • The address of a constructor cannot be referred in programs. So, pointers and references cannot be used with constructors.
  • A constructor cannot be declared as static, volatile, or const.
  • Constructors can be overloaded.
  • Constructors can have default arguments.

 

Like a member function, we can define a constructor inside or outside the class. Syntax for defining a constructor inside the class is as follows:

 

Syntax for defining a constructor outside the class is as follows:

 

Following is an example which demonstrates constructor defined inside the class:

 

Following is an example which demonstrates constructor defined outside the class:

 

Types of Constructors

 

A constructor can be classified into following types:

  1. Dummy constructor
  2. Default constructor
  3. Parameterized constructor
  4. Copy constructor
  5. Dynamic constructor

 

Dummy Constructor

 

When no constructors are declared explicitly in a C++ program, a dummy constructor is invoked which does nothing. So, data members of a class are not initialized and contains garbage values. Following program demonstrates a dummy constructor:

 

You can see that since age and branch are not initialized, they are displaying garbage values.

 

Default Constructor

 

A constructor which does not contain any parameters is called a default constructor or also called as no parameter constructor. It is used to initialize the data members to some default values. Following program demonstrates a default constructor:

 

Parameterized Constructor

 

A constructor which accepts one or more parameters is called a parameterized constructor. Following program demonstrates a parameterized constructor:

 

Copy Constructor

 

A constructor which accepts an already existing object through reference to copy the data member values is called a copy constructor. As the name implies a copy constructor is used to create a copy of an already existing object. Following program demonstrates a copy constructor:

 

In the above program you can see that there are two ways for calling a copy constructor. One way is to call the copy constructor by passing the object as a parameter (in case of s2). Other way is to directly assign an existing object to a new object (in case of s3).

 

Note: Copying an object through assignment only works during object declaration. After declaring an object, assignment just serves its basic purpose.

 

Dynamic Constructor

 

A constructor in which the memory for data members is allocated dynamically is called a dynamic constructor. Following program demonstrates dynamic constructor:

 

Constructor with Default Arguments

 

A constructor like a member function can have default arguments. The default arguments should be declared at the end of the parameters list. Following program demonstrates a constructor with default arguments:

 

Constructor Overloading

 

Declaring multiple constructors with varying number of arguments or types of arguments is known as constructor overloading. All the overloaded constructors will have the same name as that of the class. Following program demonstrates constructor overloading:

 

Destructor

 

A destructor is a special member function that is invoked automatically when the object goes out of scope and is used to perform clean up actions. Following are the characteristics of a destructor:

  • Name of the destructor is same as the class name. However, destructor name is preceded by the tilde (~) symbol.
  • A destructor is called when a object goes out of scope.
  • A destructor is also called when the programmer calls delete operator on an object.
  • Like a constructor, destructor is also declared in the public section of a class.
  • The order of invoking a destructor is the reverse of invoking a constructor.
  • Destructors do not take any arguments and hence cannot be overloaded.
  • A destructor does not return a value.
  • The address of a destructor cannot be accessed in a program.
  • An object with a constructor or a destructor cannot be used as members of a union.
  • Destructor cannot be inherited.
  • Unlike constructors, destructors can be virtual.

 

Syntax for creating a destructor is as shown below:

 

Following program demonstrates a destructor:

 

Note: If a destructor is not defined by the programmer, C++ compiler will create a inline public destructor automatically.

 

Constructors and Destructors

 

Explicit Invocation

 

Constructors and destructors can be invoked (called) explicitly from the main() function. A constructor can be invoked as shown below:

 

ClassName(params-list );

 

For example, constructor of Student class can be called as shown below:

 

Student( );

 

In case of a destructor, we need to write the class name along with the destructor name as follows:

 

object_name.ClassName::~ClassName( );

 

or

 

object_name.~ClassName( );

 

For example, destructor of Student class can be called as follows:

 

s1.~Student( );

 

A destructor can be called from a constructor as follows:

 

Similarly, a constructor can be called from a destructor as follows:

 

Private Constructor and Destructor

 

Sometimes programmers may want to prevent direct access to a constructor or destructor. In such cases, they can be made private. Access to a private constructor or destructor can be granted through public member functions or through a friend function. Following program demonstrates creating private constructors and a destructor and accessing them using public member functions:

 

Object Copy

 

Frequently while programming there will be need to create a copy of an existing object. This can be done in three ways:

 

Shallow Copy

 

In this method the copy (object) only copies the addresses (for dynamic memory) of the source object’s members. This is similar with the semantics of static data members. A same copy is shared among several objects. Similarly, in shallow copy method, both the source and copied objects share the same memory location.

 

Deep Copy

 

In this method the copied object maintains a copy of the value of each source object’s data members. To achieve this, programmer should explicitly provide a copy constructor to copy all the values of source object’s members (including dynamic memory).

 

Lazy Copy

 

This method has the advantages of the above two methods. Initially during copying, it uses shallow copying and maintains a counter to keep track of how many objects are sharing the data. When there is an attempt to modify the data, it may initiate deep copy, if necessary.

 

For more info visit this link: https://www.hackerearth.com/notes/deep-copy-and-shallow-copy/

 

Constant Objects

 

When there is a need to create a read-only object, the object can be declared as a constant object using the const keyword. Syntax for creating a constant object is as follows:

 

ClassName const object_name(params-list);

 

Following are the characteristics of a constant object:

  • Constant object can be initialized only through a constructor.
  • Data members of a constant object cannot be modified by any member function.
  • Constant object are read-only objects.
  • Constant objects should be accessed only through constant member functions.

 

Following program demonstrates a constant object:

 

Anonymous Objects

 

An object which has no name is known as an anonymous object. Syntax for creating an anonymous object is as follows:

 

ClassName(params-list);

 

An anonymous object can be created and used in any statement without using any name. It is automatically destroyed after the control moves on to the next statement. Following program demonstrates an anonymous object:

 

Following are the advantages of anonymous objects:

  • They result in cleaner, shorter, and efficient code.
  • There is no need to name objects which are going to be used temporarily.
  • No need to declare them.
  • Unnamed are objects are destroyed automatically after their use is over.

 

Anonymous Classes

 

A class which does not have a name is called an anonymous class. They are generally created when the class body is very short and only one object of that class is required. Following are the restrictions on anonymous classes:

  • Anonymous classes cannot have a constructor.
  • Anonymous classes can have a destructor.
  • Anonymous classes cannot be passed as arguments to functions.
  • Anonymous classes cannot be used as return values from functions.

 

Following program demonstrates an anonymous class:

 

 

Suryateja Pericherla

Suryateja Pericherla

Hello, I am Suryateja Pericherla working as an Asst. Professor in CSE department at Vishnu Institute of Technology. I write articles to share my knowledge and make people knowledgeable regarding certain topics.
Suryateja Pericherla

Latest posts by Suryateja Pericherla (see all)

Related Links:

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up
Thank you for visiting startertutorials.com! If you like this website do share with your friends by clicking on the social icons available on the left hand side.

As the domain name is quite large to remember, use this short domain to visit this site. Short domain: stuts.me