1

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.

jaklucky
  • 163
  • 2
  • 11

2 Answers2

5

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.

Anton Savin
  • 40,838
  • 8
  • 54
  • 90
  • Why does b2.PrintMe() calls BClass::PrintMe() even though it is initialized with DClass object? – jaklucky May 18 '15 at 20:19
  • @jaklucky because the type of `b2` is `BClass` (and [slicing](http://stackoverflow.com/q/274626/3959454) happened during the assignment). If you want virtual behavior, you can write `BClass& b2 = d` that is create a reference, or create a pointer like you did in your code. – Anton Savin May 18 '15 at 20:22
  • Thank you for the quick reply. Does slicing happens in the copy constructor/copy assignment operator? I got the virtual with b1 in my example and just playing with different combinations to understand more about it. If I use BClass& b2=d or BClass* b2 = &d; then no Slicing happens because it is just pointer assignment? Is my understanding correct? – jaklucky May 18 '15 at 20:27
1

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

ahmedsafan86
  • 1,776
  • 1
  • 26
  • 49