简体   繁体   中英

Which is the better approach to initialise the base class member while creating derive class object?

Approach 1: Initialise through constructor of dervive class

class base {
protected:
    int no;
public:
    void showData() {
        cout << no;
    }
};

class der : public base {
public:
    der(int _no) {
        no = _no;
    }
};

Approach 2: Initialise through constructor of base class

class base {
    int no;
protected:
    base(int _no) : no(_no){}

public:
    void showData() {
        cout << no;
    }
};

class der : public base {
public:
    der(int _no) : base(_no) {
    }
};

client code:

der d(10);
d.showData();

Please let me know If there is other method

You should use the second approach, with one reason: if the base class member is private , approach one won't work. It's also strange to see a derived class initializing things that don't belong to it.

Each class ctor should initialise fields in that class. So the second variant.

Obviously the second option for various reasons:

  • Let constructor of a class do its task: Construction . Let every class initialize its own data members.
  • Data members may be private, and derived class may not have access to.
  • Option 1 would involve code maintenance for ALL derived classes, and this would definitely lead to bugs.
  • Option 1 is not good appraoch as far as encapulation is concerned.

I'd strongly opt for approach 2, as the constructor may also be more complex than just initializing variables. Additionally, private members in case cannot be set in der .

The second is the correct approach. It's always best to initialize with a constructor, that's what they are for. What would you do if you had more than one derived class? What if you wanted to create base class objects by themselves? Put the initalization code in the constructor, that's how C++ is designed to work.

Always use the ctor-initializer to initialize things. Because this is the only place where you can really initialize things. Writing no=no_ anywhere will assign to an already initialized variable. For UDTs this might be a big difference, for references this is not even possible, you always have to initialize them.

So also for uniformity, use the ctor-initalizer everywhere.

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