سؤال

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 i.e. 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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top