Abstract base class with data

If I create an abstract base class and its derived classes will have the same data members, is it better to use these members in an abstract base class and provide secure access to them? Or don't bother and just put data members in derived classes. This is in C ++.

+5
source share
5 answers

If the data belongs to a derived class, let the derived class do what it wants to contain.

By placing this data in a base class (non-confidential), you force each derived class to have it. Derived classes should not be forced to do anything unless they need to populate a data element, for example. The base class defines what derived classes should do, not how they should do it.

If you find that there might be a common theme, you can create a derived class that has those elements and implementations that should then be the base class for those who want to use it. For example:

struct car
{
    virtual ~car(){}

    virtual unsigned year(void) const = 0;
    virtual const std::string make(void) const = 0;
}

// Dodge cars can feel free to derive from this instead, it just a helper
struct dodge_car
{
    virtual ~car(){}

    virtual unsigned year(void) const = 0;

    const std::string make(void) const
    {
        static const std::string result = "Dodge";
        return result;
    }

}

Etc. But you see that any derived classes still have a choice for implementing the entire car interface. It also improves code cleanliness. By supporting the real interface, implementation details will not interfere.

, , , , , , , .

+2

, : ?

( ) , . . , :

        class Human;
        class Student : public Human;

"m_Arms" "" , :

  • ? .. -, "" ? - ( ).
  • ( ) ? ( ).
  • , ? ( )

- is-a-Human, - , . - Robocop: public Human, , . , Thigh .

, . , Robocop Human , .

    class Human;
    class NormalHuman : public Human; //declare Thigh private here.
    class SuperHuman : public Human; //continue using Thigh as protected.

, , ( ) factory .

+2

?

. A Derived B , ? , .

, , , . , ?

+1

, , , , . , , .

++ . ( .) - , , .

, , , ; , , .

+1

, ( , .. ).

A base class can be virtual in the fact that only one of its methods must be implemented in a derived class. The decision that these variables and methods [of the base class] are private, protected, or even public is a separate issue.

For example, a base class may have a public method, a protected method and / or data, and several private methods.

0
source

All Articles