Created
June 19, 2024 20:33
-
-
Save john9francis/6b59a32f2951fd80d993cbf5095d4f6a to your computer and use it in GitHub Desktop.
How c++ 'this' keyword works with inheritance. Does it take the parent object or the child object?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// explanation: | |
// Defines 3 classes: Parent, Child, and Thing. | |
// Thing takes in a parent into its constructor. | |
// Parent initializes a Thing in its constructor using 'this.' | |
// Child does nothing but initialize Parent(). | |
// | |
// main initializes a Child class, and calls a function from Thing. | |
// Thing, which was initialized using 'this' in the parent constructor, | |
// uses that 'this' to refer to the Child, not the Parent. | |
#include <iostream> | |
class Parent; | |
class Thing{ | |
public: | |
Thing(Parent* p) : parent(p) {}; | |
void Print(); | |
Parent* parent; | |
}; | |
class Parent{ | |
public: | |
Parent() : myInt(0) { | |
thing = new Thing(this); | |
} | |
virtual void SetMyInt() { myInt = &parentInt; } | |
int parentInt = 1; | |
int* myInt; | |
Thing* thing; | |
}; | |
class Child : public Parent { | |
public: | |
Child() : Parent() { | |
myInt = &childInt; | |
} | |
void SetMyInt() override { myInt = &childInt; } | |
int childInt = 2; | |
}; | |
void Thing::Print() { | |
parent->SetMyInt(); | |
std::cout << *parent->myInt; | |
} | |
int main() { | |
Child child; | |
child.thing->Print(); | |
} | |
// OUTPUT: | |
// 2 | |
// | |
// This proves that even though 'Thing' was initialized in the constructor | |
// of 'Parent' using the 'this' keyword, 'this' refers to the child | |
// when the child is initialized, not the parent. This is why calling | |
// thing->Print() from the child class calls the child's 'SetMyInt()' function, | |
// not the parent's. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment