Antix
Antix

Reputation: 369

Polymorphism with class member objects

I'm wondering how polymorphism in C++ works when an object you're acting on is stored inside a class (not as a pointer or reference type).

I've read that polymorphism will only work on pointers and references, however I've overloaded the << operator, which will take in a reference to A.

In testing this example in my implementation, I find it doesn't work as expected and will return the base class string ("A") instead of "B".

Is this because the object is stored inside the class itself? and the << operator taking in a reference has nothing to do with the workings of polymorphism? (ie. because the object at it's core is stored in the class, it won't work unless I store it as a pointer/reference in the class) Thanks

class Test {

    public:
       void Run() {
           object_ = B();
           std::cout << object_ << std::endl;
       }


    private:
       A object_;
};

Class A {
    // Assume this is already implemented. All it does it add obj.getType()
    // to stream
    friend ostream& operator<<(ostream& stream, A obj);

    public:
      virtual std::string getType() {
             return std::string("A");
      }
};

Class B : public A {
    public:
      std::string getType() {
            return std::string("B");
      }
};

int main(int argc, char* argv[]) {
    Test test = Test();
    test.Run();
}

Upvotes: 2

Views: 298

Answers (1)

juanchopanza
juanchopanza

Reputation: 227390

You have an A object in your class, so when you do this:

object_ = B();

the B object on the RHS is sliced. See object slicing. This is independent of the objects being members of a class, and can be illustrated with a simpler example:

int main()
{
  B b;
  A a;
  a = b;
  std::cout << a << "\n";
}

Upvotes: 2

Related Questions