Is bad programming practice a mix of virtual and non-virtual functions in a base class?

I have a base class Base, which I declare as several polymorphic subclasses. Some of the functions of the base class are pure virtual, while others are used directly by the subclass.

(All this in C ++)

So for example:

class Base
{
protected:
     float my_float;
public:

    virtual void Function() = 0;

    void SetFloat(float value){ my_float = value}

}

class subclass : public Base
{

  void Function(){ std::cout<<"Hello, world!"<<std::endl; }
}

class subclass2 : public Base
{

  void Function(){ std::cout<<"Hello, mars!"<<std::endl; }
}

So, as you can see, subclasses would rely on the base class for a function that sets "my_float" but would be polymorphic with respect to another function.

So I wonder, this is a good practice. If you have an abstract base class, should you make it completely abstract, or is it ok to make such a hybrid approach?

+4
2

. , , . , , , , .

, , : ? , , my_float, , ,

, , , , . , , . , , , :

class DataStorage {
private:
  float data_;
public:
  DataStorage()
  : data_(0.f) {
  }

  void setFloat(float data) {
    data_ = data;
  }
};

class NotASubclass1 {
private:
  DataStorage data_;
public:
  void SetFloat(float value){ data_.setFloat(value); }  
  ...
}

class NotASubclass2 {
private:
  DataStorage data_;
public:
  void SetFloat(float value){ data_.setFloat(value); }  
  ...
}
+5

, :

  • , , Base*/Base& , Base*

    • , Base*/& s,

    • (NVI) " " - , Base*/& Base,

  • , , - , , get/set

  • , Base, , ( final, ++ 11, )

  • /, "" Base, , ,

+2

Source: https://habr.com/ru/post/1533843/


All Articles