简体   繁体   中英

What type of members can I add in a c++ abstract class

Hello lets say I have a abstract class that has a few pure abstract functions and I have a few classes that derive from this class and all the data from these classes eventually becomes similar, I was wondering if it would be wise or even possible to declare a vector under protected in the abstract class to collect the data so something like.

class A
{
protected:
    vector <string> str;
public:
    virtual function x();
    virtual function y(); //etc etc
    virtual ~A(){;}
};

class B : public A
{
public:
    function x();
    function y();
};

class C: public A
{
    //similar to class B
} ;

I am having difficulty understanding how pure virtual functions work with c++, I understand polymorphism as I have done many projects with it in java. Would it even be possible to declare and use that vector since an abstract class in c++ cant be instantiated?

Pure virtual member functions are declared as

virtual <return-type> func(<parameters>) = 0;

They are just virtual functions and they work as any other virtual function too. Usually, they don't have or need an implementation, but you may provide one if you want.

You can add any member you want to an abstract class in C++. An abstract class is just a regular class with one or more pure virtual member functions.

I was wondering if it would be wise or even possible to declare a vector under protected in the abstract class to collect the data.

Yes, lifting up data members shared among several derived types is a legitimate design choice.

What type of members can I add in a c++ abstract class?

You can add any type of members in abstract class. In general, the data members of a class should be initialized and assigned to only within the constructor and other member functions of that class. To do otherwise breaks encapsulation, thereby making maintenance and modification of the class more difficult.

I am having difficulty understanding how pure virtual functions work with c++

Specify a virtual function as pure by placing = 0 at the end of its declaration. You don't have to supply a definition for a pure virtual function.

You cannot declare an instance of an abstract base class; you can use it only as a base class when declaring other classes.

  1. I don't see any abstract classes here
  2. You can include members of any types into abstract class

More important than what, is why.

Abstract class is not just a "class with all functions made pure virtual". It represents a certain ideology in object oriented programming. When used as interfaces, they are not supposed to contain state.

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