Home > Mobile >  C change base's member variable and print it from derived class
C change base's member variable and print it from derived class

Time:06-26

The idea is:

I've 2 classes, one named Print with only one method called printName, and other class named Human with variable name. I want printName to print whatever the name variable in the Human class is.

Example:

class Print {
public:
    char name[255];  // name will be overridden from Human class.
    void print() { std::cout << name << std::endl; }  // `this.name` should be from Human class.
};

class Human : public Print {
public:
    char name[255];
};

int main() {
    Human h;
    h.name = "Somename";
    h.print(); // Should outputs: Somename
}

CodePudding user response:

One of the solutions: Curiously Recurring Template Pattern 1, 2.

template <typename T>
class Print {
public:
    char name[255];
    void print() { std::cout << static_cast<T*>(this)->name << std::endl; }
};

class Human : public Print<Human> {
public:
    char name[255];
};

int main() {
    Human h;
    h.name = "Somename";
    h.print(); // Outputs: Somename
}

h.name = "Somename" will not compile.

  • Related