Skip to content

Instantly share code, notes, and snippets.

@zaki
Last active August 29, 2015 14:10
Show Gist options
  • Save zaki/726b075dbfb70af3021d to your computer and use it in GitHub Desktop.
Save zaki/726b075dbfb70af3021d to your computer and use it in GitHub Desktop.
virtual diamonds are a programmers best enemy
class Class1
{
public:
Class1() { dummy2(); }
virtual void dummy() = 0;
void dummy2() { dummy(); }
};
class Class2 : public Class1
{
public:
virtual void dummy() { printf("Class2"); }
};
int _tmain(int argc, _TCHAR* argv[])
{
Class2 *c2 = new Class2;
delete c2;
}
class IBaseInterface
{
public:
IBaseInterface() : counter(1) {}
virtual ~IBaseInterface() {;}
virtual int getCounter() {return(counter);}
void grab() {++counter;}
private:
mutable int counter;
};
class ISimpleInterface : public virtual IBaseInterface
{
virtual void simple() {printf("simpleinterface");}
};
class ISimpleInterface2 : public virtual IBaseInterface
{
void simple2() {printf("simpleinterface2");}
};
class BaseObject : public virtual ISimpleInterface
{
virtual void work() {printf("baseobject");}
};
class BaseObject2 : public virtual ISimpleInterface2
{
void work() {printf("baseobject2");}
};
int _tmain(int argc, _TCHAR* argv[])
{
char buffer[256];
BaseObject *obj = new BaseObject();
BaseObject2 *obj2 = new BaseObject2();
void *p;
/* #1 */
p = (void*)obj;
printf("#1 Counter is %dn", ((IBaseInterface*)p)->getCounter());
/* #2 */
p = (void*)obj2;
printf("#2 Counter is %dn", ((IBaseInterface*)p)->getCounter());
/* #3 */
p = (void*)obj;
printf("#3 Counter is %dn", ((IBaseInterface*)(ISimpleInterface*)p)->getCounter());
/* #4 */
p = (void*)obj2;
printf("#4 Counter is %dn", ((IBaseInterface*)(ISimpleInterface2*)p)->getCounter());
gets(buffer);
return 0;
}
// For extra credit
class Dummy : public virtual IBaseInterface
{
virtual void dummy() = 0;
};
// [...]
int _tmain(int argc, _TCHAR* argv[])
{
/* #5 */
p = (void*)obj;
printf("#5 Counter is %dn",
((IBaseInterface*)(Dummy*)p;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment