C++ Constructors C-PLUS-PLUS

C++ Constructors  

C++ Constructors

C++ Constructors

A constructor in C++ is a special method that is automatically called when an object of a class is created. To create a constructor, use the same name as the class, followed by parentheses ().

 

How constructors are different from a normal member function?

A constructor is different from normal functions in the following ways:

  • The constructor has the same name as the class itself
  • Constructors don’t have the return type
  • A constructor is automatically called when an object is created.
  • If we do not specify a constructor, the C++ compiler generates a default constructor for us (expects no parameters and has an empty body).

Example

#include <iostream>
using namespace std;

class MyClass {     // The Class
  public:           // Access specifier
    MyClass() {     // Constructor
      cout << "Hello World!";
    }
};

int main() {
  MyClass myObj;    // Create an object of MyClass (this will call the constructor)
  return 0;
}
 

Output:

Hello World!

C++ Parameterized Constructors

 It is possible to pass arguments to constructors. 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.

Example

#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 << "Value of p1.x = " << p1.getX() << ", Value of p1.y = " << p1.getY();

  

    return 0;

}

Output:

Value of p1.x = 10, Value of p1.y = 15

Uses of Parameterized constructor:

  1. It is used to initialize the various data elements of different objects with different values when they are created.
  2. It is used to overload constructors.

Can we have more than one constructor in a class?
Yes, It is called Constructor Overloading.

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries