Created
April 5, 2022 15:24
-
-
Save stungeye/f2756619f23b3faace49da04193d127b to your computer and use it in GitHub Desktop.
Base and Derived Classes and Objects in C++ (With References and Pointers)
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
#include <iostream> | |
#include <string> | |
class Base { | |
protected: | |
int value{0}; | |
public: | |
Base(int value) : value{value} { | |
std::cout << "Base Constructor\n"; | |
} | |
std::string getName() const { | |
return "Base"; | |
} | |
int getValue() const { | |
return value; | |
} | |
}; | |
class Derived : public Base { | |
public: | |
Derived(int value) : Base{value} { | |
std::cout << "Derived Constructor\n"; | |
} | |
std::string getName() const { | |
return "Derived"; | |
} | |
int getDoubleValue() const { | |
return value * 2; | |
} | |
}; | |
void printDetails(const Derived& derivedRef) { | |
std::cout << "printDetail by Reference\n"; | |
std::cout << derivedRef.getName() << " : " << derivedRef.getValue() << " : " | |
<< derivedRef.getDoubleValue() << "\n"; | |
} | |
void printDetails(const Derived* derivedPointer) { | |
std::cout << "printDetail by Pointer\n"; | |
std::cout << derivedPointer->getName() << " : " << derivedPointer->getValue() << " : " | |
<< derivedPointer->getDoubleValue() << "\n"; | |
} | |
int main() { | |
Base base{25}; | |
std::cout << base.getName() << " : " << base.getValue() << "\n"; | |
Derived derived{10}; | |
std::cout << derived.getName() << " : " << derived.getValue() << " : " | |
<< derived.getDoubleValue() << "\n"; | |
const Derived& derivedRef{derived}; | |
std::cout << derivedRef.getName() << " : " << derivedRef.getValue() << " : " | |
<< derivedRef.getDoubleValue() << "\n"; | |
printDetails(derived); | |
const Derived* derivedPointer{&derived}; | |
std::cout << derivedPointer->getName() << " : " << derivedPointer->getValue() << " : " | |
<< derivedPointer->getDoubleValue() << "\n"; | |
printDetails(&derived); | |
Base& baseRefToDerived{derived}; | |
Base& baseRefToBase{base}; | |
Base* basePointerToDerived{&derived}; | |
std::cout << baseRefToBase.getName() << " : " << baseRefToBase.getValue() << "\n"; | |
std::cout << baseRefToDerived.getName() << " : " << baseRefToDerived.getValue() << "\n"; | |
std::cout << basePointerToDerived->getName() << " : " << basePointerToDerived->getValue() << "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment