Constructors

Like we can initialize a variable, we can also initialize an object of a class.
See this example,

    class A
    {
        public:
        int a;
        int b;
        … …
        other members
        … …
    };
    A obj = {1,2};

obj is initialized with {1,2}, this means first member of obj which is ‘a’ gets the value of 1 and second member of obj which is ‘b’ gets the value of 2.
But objects can only be initialized like this when the data members are public.
Consider the following example,

    class A
    {
        int a;
        int b;
        public:
        … …
        other members
        … …
    };
    A obj = {1,2};      //error!!

As we can see that data members ‘a’ and ‘b’ of class A are private, so it’s an error to initialize them with a initializer list ({1,2} is called an initializer list, because they are used for initialization).
So what is the correct way to initialize them? Constructors.
A constructor is a member function of a class that is automatically called when an object is created for a class.
Even if we don’t define it explicitly, it is always implicitly called by a class.
If we explicitly define a constructor, it overwrites the implicit version of it.
Let’s see an example,

    class A
    {
        int a;
        int b;
        public:
        … …
        A()
        {
            a = 1;
            b = 2;
        }
    };
    A obj;

Now ‘a’ and ‘b’ are initialized to 1 and 2 respectively.
Some might argue that this is assignment rather than an initialization.
But no, constructors initialize data members, it is same as
int a = 4; As we don’t say this statement an assignment, rather we call it an initialization in the same way constructors are used to initialize data members irrespective of their access level.

Some Points about Constructs

  1. Constructors are of the same name as that of a class, with same capitalization with no return type, not even void
  2. Constructors must always be public
  3. Compiler automatically calls the constructor when it creates a particular object, there is no need for us to explicitly call the constructor.
  4. Mainly constructor is used to initialize data members of the class, though it can be put to other uses.
  5. A constructor with no parameters passed is a default constructor. For class Employee, Employee() is the default constructor.

Sample Program illustration

#include <iostream>
#include <string>
using namespace std;
class Emp
{
    int empId;
    string name;

public:
    Emp()
    {
        empId = 1;
        name = "Eve";
    }
    void print()
    {
        cout << empId << endl;
        cout << name << endl;
    }
};
int main()
{
    Emp e1;
    e1.print();
}

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?