The idea is:
I've 2 classes, one named
printName, and other class namedHumanwith variablename. I wantprintNameto print whatever thenamevariable in theHumanclass 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.
