You cannot magically cast one object into another1. Fortunately, there's no need whatsoever to do that. You can just dereference the pointer to get the object being pointed at.
#include <iostream>
class ClassTwo
{
public:
void method2(){std::cout << "I am a ClassTwo method!" << std::endl;};
};
class ClassOne
{
public:
void method1(){};
ClassTwo* ptr;
};
int main()
{
// create object of type ClassOne
ClassOne someObject;
// create object of type ClassTwo
ClassTwo someOtherObject;
// make ClassOne's pointer point at the second object
someObject.ptr = &someOtherObject;
// Use the first object to call the method in the second object
someObject.ptr->method2();
// Alternative notation for the same thing
(*someObject.ptr).method2();
return 0;
}
1. Actually, you can, but it's telling the compiler to trust you and the compiler will happily let you go very badly wrong. It's dangerous and asking for trouble (and wouldn't work in this case either).
But I would like to achieve it without using the pointer in Class One.
Classoneobject->method1;
Classoneobject->method2;
What I would like to do is: the code automatically chooses the right method. If the object has the method, it runs it. If it doesn't find it, it casts itself to Classtwoobject and tries to find the method there.
class Operation
{
public:
virtualvoid doOperation()=0;
}
class ClassTwo : public Operation
{
public:
void method2(){std::cout << "I am a ClassTwo method!" << std::endl;};
void doOperation(){ method2(); }
};
class ClassOne : public Operation
{
public:
void method1(){};
void doOperation(){ method1(); }
ClassTwo* ptr;
};
You can also do this with static polymorphism, however, what you are asking doesn't make sense for ClassOne and ClassTwo they have no 'has a' or 'is a' relationship.
What I would like to do is: the code automatically chooses the right method. If the object has the method, it runs it. If it doesn't find it, it casts itself to Classtwoobject and tries to find the method there.
Are you asking the compiler to notice that you're calling a function that doesn't exist, and to then go searching through all the other objects it knows about, and find one that contains a function with the same name, and to call that function instead? That is insane.
Are you perhaps thinking of inheritance and virtual functions (as Clanmjc has written)?