Home > other >  C Child Class Change Parent Class's Constructor
C Child Class Change Parent Class's Constructor

Time:06-29

Modified the question a bit, thanks for your help on this!

Is there a way to change Parent's constructor(e.g. change the value of protected field) when initialize the Child class.

For example, I have two class - Base and Child below. In the Base constructor, string 'a' will be assigned to a protected field - 'a_' and 'val'(e.g. if a is "str", then a_ is 'a', val is 'a!').

There is a Child class that inherits class Base, and the constructor takes two arguments - string a and b.

What I want is assign 'a b "!"' to val, e.g. a = "first ", b = "second", then a_ is "first", b_ is "second", c's value should be "first second!"

class Base {
   public:
     explicit Base(string a) : a_(a), val(a   "!"){};

   protected:
      string a_;
      string val;
}

class Child : public Base {
   public:
     explicit Child(String a, String b) : Base(a), b_(b)...
   
   protected:
      string b_;

}

CodePudding user response:

You can do it like this. By providing a public getter you can also hide implementation details from your derived classes and from your clients making both classes more maintainable. (I hardly ever use protected members)

#include <string>
#include <iostream>

// using namesapce std;  NO not recommended
// https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

class Base
{
public:
    explicit Base(std::string a) : val(a) {};

    const std::string& get() const noexcept
    {
        return val;
    }

private:
    std::string val;
};

class Child : public Base
{
public:
    explicit Child(std::string a, std::string b) :
        Base(a   b)
    {
    }
};

int main()
{
    Child c("Hello", "World");
    std::cout << c.get();
    return 0;
}

CodePudding user response:

Try to use the Reference variable for either child or parent while accessing the protected member.

  • Related