Your classes don't contain virtual functions. In particular, if polymorhism was at work here, all set's should call C::set. Without the virtual keyword they don't.
Code:
#include <iostream>
class A{
public:
//virtual //uncomment to see the difference
void set(int z){std::cout << "A::set\n"; a = z;};
int a;
};
class B : public A{
public:
int c;
void hello(){};
void set(int z){std::cout << "B::set\n"; b = z;};
int b;
};
class C : public B{
public:
void set(int z){std::cout << "C::set\n"; c = z;};
int c;
};
int main()
{
A *test = new C;
test->set(1);
B *foo = static_cast<B*>(test); // I understand why it fails because the pointer is technically of class A, but is this safe?
foo->set(1);
C *bar = static_cast<C*>(test);
bar->set(1);
delete test;
return 0;
}
However, if that is what you want, it seems that you can create a simple instance and call the desired version of set manually (not that it seems like a really great way to use classes and inheritance):
Code:
#include <iostream>
class A{
public:
void set(int z){std::cout << "A::set\n"; a = z;};
int a;
};
class B : public A{
public:
int c;
void hello(){};
void set(int z){std::cout << "B::set\n"; b = z;};
int b;
};
class C : public B{
public:
void set(int z){std::cout << "C::set\n"; c = z;};
int c;
};
int main()
{
C test;
test.set(1);
test.B::set(1);
test.A::set(1);
return 0;
}