简体   繁体   中英

Defining functions in derived classes

Suppose I have one base class fruit and three derived classes say Apple,orange and mango.Now I want to define one member function "taste" in Apple class only.So how can I do that? Is it necessary to define it in base class and all the derived classes Or I can define it in only one desired class ie apple Do I have to use virtual function for that

Thanks and Regards

You don't have to define it in base class. However, you will not be able to call this method on base class pointer or reference though. The function doesn't need to be virtual.

class Fruit {};
class Apple : public Fruit
{
public:
    void Taste();
}

class Orange : public Fruit {}
class Mango : public Fruit {}

Fruit* f = new Apple();
f->Taste(); // Error
Apple* a = new Apple();
a->Taste() // Ok

If however you want to have access to the method from base class pointer or reference, you need to define a empty implementation of a virtual method in base class and override it in Apple class.

class Fruit
{
public:
    virtual void Taste() {}
};
class Apple : public Fruit
{
public:
    virtual void Taste()
    {
        // Do something.
    }
}

class Orange : public Fruit {}
class Mango : public Fruit {}

Fruit* f = new Apple();
f->Taste(); // Ok
Fruit* f2 = new Orange();
f2->Taste(); // Ok and no side effect.

in general design pattern that class behavior and qualities should be added as a pattern, in a different sub class called taset.

this is a good example for ducks, this apply for your fruit as well

http://www.cs.colorado.edu/~kena/classes/5448/f09/lectures/16-introdesignpatterns.pdf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM