jaklucky
jaklucky

Reputation: 163

Constructor not being called during assignment

I am trying to understand the following code.

I created two classes BClass and DClass as follows.

//My Header file

class BClass
{
    public:
        BClass();
        ~BClass();
    virtual void PrintMe() const;
};

class DClass : public BClass
{
    public:
        DClass();
        ~DClass();
    void PrintMe() const;
};

//My cpp file

BClass::BClass()
{
}


BClass::~BClass()
{
}

void BClass::PrintMe() const
{
    printf("This is base class \n");
}

DClass::DClass()
{
}

DClass::~DClass()
{
}

void DClass::PrintMe() const
{
    printf("This is derived class \n");
}

//My main file

BClass b; //BClass constructor called
b.PrintMe();

DClass d; //DClass constructor called
d.PrintMe();

BClass* b1 = &d; //No constructor called as it is pointer assignment
b1->PrintMe();

BClass b2 = d;  //No constructor called...expecting BClass constructor to be called???
b2.PrintMe();

At the last section, I was expecting that BClass constructor to be called. But it did not. Could someone please explain me what is going on?

If do like this, we know BClass constructor is called

BClass b2; //BClass constructor called
b2 = d;  

Could some one explain the difference between

BClass b2 = d;

and

BClass b2; 
b2 = d;

Thank you.

Upvotes: 1

Views: 67

Answers (2)

ahmedsafan86
ahmedsafan86

Reputation: 1794

The copy constructor is called instead look at this http://en.cppreference.com/w/cpp/language/copy_constructor

BClass b2 = d;

The copy constructor is called, if you don't implement it it automatically generated by the compiler

BClass b2; //The default constructor is called at line 1
b2 = d;//The assignment operator is called

implement copy constructor and assignment operator, print hints to see the difference

Upvotes: 1

Anton Savin
Anton Savin

Reputation: 41301

BClass b2 = d; calls copy constructor of BClass, which is implicitly generated by the compiler because all conditions for its implicit generation are met.

BClass b2; b2 = d; calls default constructor of BClass and then it calls the copy assignment operator, which is also implicitly generated.

Upvotes: 5

Related Questions