In Inheritance: can I override base class data elements?

Let's say I have two classes:

Class A
{
public:
..
private:
  int length;
}

Class B: public Class A
{
public:
..
private:
 float length;
}

What I would like to know:

  • Is overriding data elements of a base class allowed?
  • If so, is this a good practice?
  • If not, how can you extend the type of data elements of a class?

There is a class that satisfies my needs, and I want to reuse it. However, for my program needs, its data members must be of a different type.

I have several books, but all of them relate only to the redefinition of base class class methods.

+3
source share
4 answers

You can use template elements, that is, common elements, rather than overriding elements.

VARIANT (COM) .

   struct MyData
   {
        int vt;              // To store the type

        union 
        {                
            LONG      lVal;
            BYTE      bVal;
            SHORT     iVal;
            FLOAT     fltVal;
            .
            .
        }
   };
+7

1) , . // , .

2) , . ;)

3) , .

+3

++, , , , . A float length - int length.

++, . , , , .

+3

1) , , ,

2) ! . - , , undefined.

3) . , "has-a" "is-a".

0

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


All Articles