close

Abstract class is also called interface class . An interface class is a class that has no members variables, 

and where all of the functions are pure virtual! In other words, the class is purely a definition, and has no actual implementation.

pure virtual function (or abstract function) that has no body at all! 

A pure virtual function simply acts as a placeholder that is meant to be redefined by derived classes.

Using a pure virtual function has two main consequences: 

First, any class with one or more pure virtual functions becomes anabstract base class, which means that it can not be instantiated!

Second, any derived class must define a body for this function, or that derived class will be considered an abstract base class as well.

This helps ensure the derived classes do not forget to redefine functions that the base class was expecting them to.

A pure virtual function is useful when we have a function that we want to put in the base class, 

but only the derived classes know what it should return. 

 

To create a pure virtual function, rather than define a body for the function, we simply assign the function the value 0.

 

class Animal
{
protected:
    std::string m_strName;
 
public:
    Animal(std::string strName)
        : m_strName(strName)
    {
    }
 
    std::string GetName() { return m_strName; }
    virtual const char* Speak() = 0; // pure virtual function
};


class Cow: public Animal
{
public:
    Cow(std::string strName)
        : Animal(strName)
    {
    }
 
    virtual const char* Speak() { return "Moo"; }
};
 
int main()
{
    Cow cCow("Betsy");
    cout << cCow.GetName() << " says " << cCow.Speak() << endl;
}

 

Attention :

1.  In the derived class , the keyword , virtual , is optional.

2.  Instance (computer science) can refer generally to any running process, or specifically to an object, as in an instance of a class. 

The process of creating a new object (or instance of a class) is often referred to as instantiation.

(ref : http://en.wikipedia.org/wiki/Instantiation )


ref : http://www.learncpp.com/cpp-tutorial/126-pure-virtual-functions-abstract-base-classes-and-interface-classes/

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JerryCheng 的頭像
    JerryCheng

    KwCheng's blog

    JerryCheng 發表在 痞客邦 留言(0) 人氣()