Skip to content

Instantly share code, notes, and snippets.

@stungeye
Created April 5, 2022 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stungeye/f2756619f23b3faace49da04193d127b to your computer and use it in GitHub Desktop.
Save stungeye/f2756619f23b3faace49da04193d127b to your computer and use it in GitHub Desktop.
Base and Derived Classes and Objects in C++ (With References and Pointers)
#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