kvway
kvway

Reputation: 494

Forbid inheritance

I have a parent class:

 class Animal
    {
    public :
       virtual void SetColor ( const string & col )
       {
         colour = col;
       }  

       virtual void Greeting ( const string & name )
       {
         cout << "Hi I'm Animal" << endl;
       }
    protected:
     string colour;
    };

Then i have a class Dog that inherit from class Animal.

For example :

class Dog : public Animal
{

};

If I'm not mistaken the Dog child class inherits everything from parent class Animal so in this case the Dog class inherits 2 methods SetColor and Greeting and also string colour.

Is it possible to forbid method "Greeting" in parent class Animal to inherit?

Upvotes: 0

Views: 97

Answers (1)

wally
wally

Reputation: 11002

You can force Dog to provide its own Greeting:

#include <iostream>
#include <string>

class Animal {
public:
    virtual void SetColor(const std::string & col)
    {
        colour = col;
    }

    virtual void Greeting(const std::string & name) = 0;

protected:
    std::string colour;
};

class Dog : public Animal {

    virtual void Greeting(const std::string & name) override
    {
        std::cout << "Hi I'm a dog. My name is " << name << ". I was forced to provide this function.\n";

    }
};

int main(void)
{
    Animal *ptr = new Dog();
    ptr->Greeting("Fluffy");
    delete ptr;
    return 0;
}

Upvotes: 1

Related Questions