Matt Hollands
Matt Hollands

Reputation: 131

Method returning base class rather than derived class c++

I'm coming from a C# background so I hope this makes sense.

I have a base class and a derived class. I would like to be able to define a method that operates on any class derived from the base and then return the object itself. Here is an example:

class base
{
public:
    virtual void print()
    {
        cout << "Base" << endl;
    }
};

class derived : public base
{
public:
    void print()
    {
        cout << "Derived" << endl;
    }
};

int main()
{
    derived a;
    a.print();
    base b = doPrint(a);
    b.print();
}

base doPrint(base obj)
{
    obj.print();
    return obj;
}

The output I get is

Derived
Base
Base

What I would like to get is "Derived \n Derived \n Derived" ie I would like the object to be treated as a Derived class the whole time. This is important because it could be returning any class derived from base.

How can I do this? Does it have something to do with generic classes?

Thanks

[Edit] Could this be done by putting the "doPrint" method into a class with a generic type that I could assign to be Derived class?" [/Edit]

Upvotes: 1

Views: 219

Answers (1)

Quentin
Quentin

Reputation: 63114

Parameter passing works by copy in C++, and there are no implicit pointers. Thus when you call doPrint it instanciates a new Base from its parameter. If you want to pass the Derived instance itself, you must do so via a pointer or a reference :

base &doPrint(base &obj)
//   ^            ^
{
    obj.print();
    return obj;
}

Upvotes: 4

Related Questions