Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy constructor of base and derived classes

Tags:

c++

I have those two classes

///////////BASE CLASS

    class Base{
    public:
     Base(int = 0);
     ~Base();
     Base(Base&);
     Base(Derived&);   ////<-may be problem here?, note: I tried without this function
     int valueOfBase();
    protected:
     int protectedData;
    private:
     int baseData;
    };

    /////////////DERIVED CLASS
    class Derived: public Base{
    public:
     Derived(int);
     //Derived(Derived&);
     ~Derived();
    private:
     int derivedData;
    };

and here my main

    int main(){
     Base base(1);
     Derived derived = base;
    return 0;
    }

I read that if my derived class doesn't have copy c'tor copy c'tor of the base will be called but every time I receive conversion from Base to non-scalar type Derived requested who is wrong? my compiler or my book, or I've just misunderstood? thanks in advance

like image 323
rookie Avatar asked Oct 03 '10 08:10

rookie


People also ask

How do you write a derived class copy constructor?

class some_class { public : some_class(some_class const &instance_); // Copy-constructor some_class(some_class &instance_); // Default constructor }; When dealing with inheritance, be sure to invoke the base-copy-constructor, because otherwise, the base will not be affected.

What is the copy constructor of a class?

Copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. Copy constructor takes a reference to an object of the same class as an argument.

Can we inherit copy constructor?

Copy constructor is not inherited.


1 Answers

Just a hint.

Does the following code give the same error?

class base{};
class derived: public base{};

int main()
{
      derived d= base();
}

Yes? Why? Because there is no conversion from the base class to the derived class. You should define this conversion if you want your code to compile.

How about adding this to the derived class ?

derived(const base &b){} 

Makes sense, huh?

like image 199
Prasoon Saurav Avatar answered Oct 25 '22 03:10

Prasoon Saurav