Copy Constructor in C++

What is copy constructor? “A copy constructor is used to declare and initialize an object from another object.” “Constructor which accepts a reference to its own class as a parameter is called copy constructor.“ Look at below code: The process of initializing through a copy constructor is known as copy initialization. Here, t2=t1 will not invoke copy constructor. t1 and t2 are objects, assigns the values of t1 to t2. A copy constructor takes a reference to an object of the same class as itself as an argument. Example: The…

Read More

Parameterized Constructor in C++

The constructors that can take arguments are called parameterized constructors. Using parameterized constructor we can initialize the various data elements of different objects with different values when they are created. Example: When a constructor has been parameterized, the object declaration statement such as item t; may not work. We must pass the initial values as arguments to the constructor function when an object is declared. This can be done in 2 ways: Example:

Read More

Default Constructor in C++

A constructor that accept no parameter is called the default constructor. The default constructor for class A is A :: A( ). If no such constructor is defined, then the compiler supplies a default constructor. A default constructor is one which can be called with no arguments. Most commonly, a default constructor is declared without any parameters, but it is also possible for a constructor with parameters to be a default constructor if all of those parameters are given default values. Example:

Read More

Constructor in C++

C++ provides a special member function called the constructor which enables an object to initialize itself when it is created. What is Constructor ? “A constructor is a special member function whose task is to initialize the objects of its class.” It is special because its name is the same name as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class. Syntax: A constructor is declared and defined…

Read More