-2

I have a base class that is inherited into a derived class. I then instantiate both base and derived objects.

class Base
    { public : 
            Base() {} 
         ~Base) {}  };

class Derived : public Base
    { public : 
            Derived() {} 
         ~Derived() {}  };

Base b;
Derived d;
Derived::Base::d = b;

Now I'd like to copy the base class object (b) into the derived class object (d) in place of it's inherited base class. Any ideas on the syntax?

G.Fisher
  • 1
  • 1
  • Anything accepting a base with accept a derived, if base is copyable 'Base b = d;' should work. – gan_ Oct 06 '15 at 15:57
  • What are you *really* trying to do? http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – Karoly Horvath Oct 06 '15 at 15:59
  • *"Any ideas on the syntax?"* - That's not a question on a specific problem. Stackoverflow is about specific problems with specific solutions. – Christian Hackl Oct 06 '15 at 16:37

2 Answers2

1

What I think you're trying to say is that you want to initialize the data members of a Derived to those members from some Base.

You can do this with a copy constructor in Base, and a corresponding constructor in Derived that passes the value on.

Code:

class Base
{ 
    public : 
        Base() { /*...*/}
        Base(const Base& other){/*...*/}
        virtual ~Base() {/*...*/}  
    private:
        /*...*/
};

class Derived : public Base
{ 
    public : 
        Derived() {/*...*/} 
        ~Derived() {/*...*/} 
        Derived(const Base& other) : Base(other){/*...*/}

};

int main()
{
    Base b;
    Derived d(b);
}

You can do similar operations for forwarding constructors and assignment operators.

AndyG
  • 39,700
  • 8
  • 109
  • 143
0
Derived::Base::d = b;

Any ideas on the syntax?

It's wrong. Options for a working syntax would include:

  • static_cast<Base&>(d) = b;
  • d.Base::operator=(b1);

Both are pretty ugly; a result of the fact that the assignment operator in the subclass hides the base version. As is often the case in C++, the ugliness of the syntax indicates that this kind of operation is unusual and that refactoring may be a good idea.


Generally, operator overloading and inheritance don't mix well, especially if you are using inheritance for object-oriented programming (i.e. with virtual functions). In that case, one typically makes sure that the class is not assignable at all (which C++11 makes very easy because you simply delete the generated assignment operator in the base class).

You should also read more about object slicing, for example all answers and comments for these two questions:

Community
  • 1
  • 1
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62