Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Inheritance with pure virtual functions

I'm trying to create a class that serves as a base object, which will then be sub-classed (=implemented) to serve various purposes.

I want to define one or more pure virtual functions, so that however subclasses the base class, is required and does not forget to implement them.

There is one caveat, the pure virtual function's signature includes the type of the base object. Once sub-classed, the function definition doesn't match the base classes definition anymore of course. E.g.:

class BaseItem 
{
public:
    virtual std::string getDifferences(const BaseItem& item) = 0;
}

So, in the derived class I'd like to do:

class DerivedClass : public BaseItem
{
public:
    virtual std::string getDifferences(const DerivedClass& item) = 0;
private:
    std::string derivedItemCustomObject;
}

which of course the compiler won't accept. I could make it a BaseItem of course, but then I can't utilize any objects in the derived class.

Do I have to use casting to accomplish this?

Please let me know if my intent/question is not clear.

like image 782
Lucky Luke Avatar asked Jan 20 '23 18:01

Lucky Luke


1 Answers

There is NO need to change the function signature. Look at following:

class BaseItem 
{public:
    virtual std::string getDifferences(const BaseItem& item) = 0;
};

class DerivedClass : public BaseItem
{public:
    virtual std::string getDifferences(const BaseItem& item)  // keep it as it's
    {
       const DerivedClass& derivedItem = static_cast<const DerivedClass&>(item);
    }
};

Can use static_cast<> without any fear because, DerivedClass::getDifferences() is called only for DerivedClass object. To illustrate,

BaseItem *p = new DerivedClass;
DerivedClass obj;
p->getDifferences(obj);  // this always invoke DerivedClass::getDifferences

If you worry that sometime you might end up passing any other derived class object as an argument to the method, then use dynamic_cast<> instead and throw exception if that casting fails.

like image 152
iammilind Avatar answered Jan 29 '23 08:01

iammilind