puppydog puppydog - 2 months ago 6
C++ Question

Setting child class attributes through constructors: Bad practice?

I'm using a base class to declare the main attributes and functions to manipulate those attributes of a family of classes I'll define later. I've found that redefining class variables in child classes doesn't actually have any effect and have been define

type members to set values as seen below.


#include <iostream>

class Base {
void set_val(const char& c) { val = c; }
void print_val() { std::cout << "Val = " << val << std::endl; }
char val = 'a';

class Derived : public Base {
char val = 'c'; // No effect
char derived_val = 'b';
// Constructor assigns derived_val to val
Derived() { set_val(derived_val); };

int main(int argc, const char * argv[]) {
Base base;
base.print_val(); // 'a'
Derived derived;
derived.print_val(); // 'b'


Val = a
Val = b

Now this works but I'm not sure if it's the best way to do it, or even if it's a good practice to use class inheritance this way. Could someone enlighten me?


I wouldn't exactly say that it is bad practice, just completely unnecessary.

The reason why

char val = 'c';

has no effect because you are defining a new val in Derived, which hides the val in Base. When you call print_val, it only sees Base::val, not Derived::val. And so it prints Base::val.

You can change Base::val directly in the constructor of Derived, instead of redefining it:

Derived() { val = 'c'; }