Skip to content

Instantly share code, notes, and snippets.

@MacDada
Last active July 16, 2022 18:32
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 MacDada/55777de633b75f70b7f0a7e38ed1acaf to your computer and use it in GitHub Desktop.
Save MacDada/55777de633b75f70b7f0a7e38ed1acaf to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
class Bar {
public:
Bar(int a, int b): a(a), b(b) {};
// a is mutable property, b isn't – by the contract of object's public interface
void setA(int _a) { a = _a; }
int getA() { return a; }
int getB() { return b; }
private:
int a;
int b;
};
// fak em all, look brah what i'm cooking here
class CrazyBarByFoo: public Bar {
public:
CrazyBarByFoo(): Bar(0, 0) {}
int getA() { return 404; }
// the number of the Beast, cause im craaaaaazeeeeeeyyy!
int getB() { return 666; }
private:
using Bar::getA;
using Bar::getB;
};
class Foo {
public:
explicit Foo(Bar &bar): bar(bar) {}
void prettyPleaseTalkWithBar1() {
// yea, Foo is a good boi - using Bar's public interface as it should be
bar.setA(7);
}
void prettyPleaseTalkWithBar2() {
// boooooo, Foo is a nasty bastard, it is replacing Bar it was given by entirely different Bar!
Bar barReplacement{69, 69}; // yea, im feeling nasty
bar = barReplacement;
}
void prettyPleaseTalkWithBar3() {
// praise the Satan, muahaahahhaahahahaa!
CrazyBarByFoo crazyBar;
bar = crazyBar;
}
private:
Bar &bar;
};
int main()
{
Bar outsideBar{2, 3};
Foo foo{outsideBar};
// I gave you a Bar, so be kind and talk with it
// [a Bar will be willing to talk if you speak its public interface ofc]
foo.prettyPleaseTalkWithBar1();
cout << outsideBar.getA() << endl; // cool, you talked with Bar and it changed its "a" to 7 - how nice!
cout << outsideBar.getB() << endl; // "b" is still 3 – as it was given to Bar by its birthright
// hey guys, lets talk again! keep the good communication comming :-)
foo.prettyPleaseTalkWithBar2();
cout << outsideBar.getA() << endl; // haha, very funny, after u talked Bar changed its "a" to 69 <3
cout << outsideBar.getB() << endl; // DA FAK! what has happened in here?! did you kill my Bar and think I woudn't notice?!
// ok, you have one more change, please don't be a disappointment
foo.prettyPleaseTalkWithBar3();
// now it got interesting: getA and getB are called upon the Bar class, not from the CrazyBarByFoo class
// not bad after all – CPP could be much more EVIL :P
// …unless…
// …unless it can still be much more evil, but im still too much of a noobie to make it evil :P
cout << outsideBar.getA() << endl;
cout << outsideBar.getB() << endl;
return 0;
}
todo:
https://www.geeksforgeeks.org/copy-constructor-vs-assignment-operator-in-c/
im a noob getting roasted:
https://discord.com/channels/583251190591258624/742849025191051326/997845160723488808
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment