Is inheritance a base class without virtual bad practices?

I read the answer some time ago to a question regarding dynamic_cast. Dynamic_kata did not work because the base class did not have virtual methods. One answer said that outputting from classes without virtual methods usually means poor design. It's right? Even without using polymorphism, I still do not see an error in this.

+5
source share
5 answers

It depends on what we are talking about:

  • for class classes (no data), this is good ( std::unary_functioncomes to mind)
  • private ( , ) .

, Derived . - , .

. , , .

+6

.

. - . , - , , - .

+2

++ - , . .

0

, ( ):

struct some_policy
{
    // Some non-virtual interface here
protected:
    ~some_policy() { ... }

private:
    // Some state here
};

struct some_class : some_policy, some_other_policy { ... };

, . :

struct base_vector
{
    // Put everything which doesn't depend 
    // on a template parameter here

protected:
    ~base_vector() { ... }
};

template <typename T>
struct vector : base_vector
{ ... };

, CRTP. :

template <typename Base>
struct some_concept 
{
    void do_something { static_cast<Base*>(this)->do_some_other_thing(); }

protected:
    ~some_concept() { ... }
};

struct some_class : some_concept<some_class> { ... };

, Empty Base Optimization. , , some_class ( ).

template <typename T>
struct some_state_which_can_be_empty { ... };

template <typename T>
struct some_class : private some_state_which_can_be_empty<T> { ... };

, , , , .

0

++ ( ), -. I.e., , . , , , .

hth.,

0

All Articles