Sign in to follow this  
fotogames

Pointer to class type?

Recommended Posts

Hello everyone!

I was wondering if anyone knows if it is possible in C++ to make a pointer to a class type, or something in that direction... I don't think it is, but maybe I'll get lucky :) I know I can make a pointer to a class this way:

myClass* classPointer;

But that's not what I'm looking for. I'm looking for a feature where you can make a variable contain a class type. I mean something like this:

[CODE]
class myClass1{};
class myClass2{};

sometype classContainer = &myClass1;

classContainer = &myClass2;

pointerToClass classPointer = new classContainer;
[/CODE]

Kinda like this... I guess the two classes (myClass1 & myClass2) need to inherit the same class or something like that. Is this possible? Is it very complicated? If it is just say so :P I guess this is a really weird way of accomplishing what I want and I don't really need this so if it isn't possible or very hard it doesn't matter, I guess i'm still a beginner ^^.

Thanks in advance!

Share this post


Link to post
Share on other sites
I think you are trying to get a result in the wrong way. If you explain what you really want to do, then it is easier to find a design that gives you what you need.

It is possible, and also quite common, to have classes inherit from a common base class. When you do that, you can have a pointer to the base class type, and initialize it with one of the derived classes. However, if you have functionality outside of the class that asks the class what type it is and then have conditional functionality from this, then you have missed the idea with OO.

The common pattern is to have a pointer to the base class, and a common method that is then overrided by each sub class. That method will then implement the different behavior. This design pattern allows for more flexibility.

Share this post


Link to post
Share on other sites
This is not possible in C++. Classes in C++ are no objects and therefore it is not possible to store them in a variable. It is possible in different languages (e.g. Java, Smalltalk...).

What problem are you trying to solve with this? Looks to me like you want to implement some kind of factory pattern with this?!

Share this post


Link to post
Share on other sites
Thanks for the responses! I'm trying to make some kind of state machine, and I wanted to be able to tell the machine which class the state machine had to make (sounds weird but my english vocab is not broad enough to explain it clearer than this :P) However I've been thinking and I don't think I need an infinite state machine, so I'm going to go with a finite state machine. Thanks for the help guys :)

Share this post


Link to post
Share on other sites
What is your high level goal here?

You cannot have a pointer to a class. If the classes are related, you can use a pointer-to-base class with a factory to build a derived class at runtime.

If the classes are not related, a template may suit.

Share this post


Link to post
Share on other sites
Of course it's possible. How else would you allocate a class on the heap? When you "new" you get a pointer to your class. If it's a pointer to a base class then like another poster said the actual class would implement the different behaviour. It's how I implement gamestates but I digress.

Share this post


Link to post
Share on other sites
[quote name='brx' timestamp='1341562552' post='4956253']
This is not possible in C++. Classes in C++ are no objects and therefore it is not possible to store them in a variable. It is possible in different languages (e.g. Java, Smalltalk...).

What problem are you trying to solve with this? Looks to me like you want to implement some kind of factory pattern with this?!
[/quote]

This isn't really correct. Using pointers you can do many flexible things, including storing different class types in a single pointer variable, but you should truly understand what you are doing. If inheriting from a base class won't work, then I'd be very careful going about this solution.

Share this post


Link to post
Share on other sites
[quote name='Fredericvo' timestamp='1341581417' post='4956318']
Of course it's possible. How else would you allocate a class on the heap? When you "new" you get a pointer to your class. If it's a pointer to a base class then like another poster said the actual class would implement the different behaviour. It's how I implement gamestates but I digress.
[/quote]
Ehm... you do not allocate CLASSES on the heap but OBJECTS (i.e. instances of a class). If I understand the initial post correctly, he wants to store a pointer to the CLASS and then later use that pointer to create an instance of the class. In Java, for example you can actually have a variable of the type "Class" and call the method "newInstance" on it which will create an object. This is not possible in C++.

[quote name='BeerNutts' timestamp='1341584099' post='4956329']
This isn't really correct. Using pointers you can do many flexible things, including storing different class types in a single pointer variable, but you should truly understand what you are doing. If inheriting from a base class won't work, then I'd be very careful going about this solution.
[/quote]
Again, you store a pointer to an instance of a class not to the class itself. This would only be possible if classes were actual objects which they are not in C++. Edited by brx

Share this post


Link to post
Share on other sites
[quote name='BeerNutts' timestamp='1341584099' post='4956329']
[quote name='brx' timestamp='1341562552' post='4956253']
This is not possible in C++. Classes in C++ are no objects and therefore it is not possible to store them in a variable. It is possible in different languages (e.g. Java, Smalltalk...).

What problem are you trying to solve with this? Looks to me like you want to implement some kind of factory pattern with this?!
[/quote]

This isn't really correct. Using pointers you can do many flexible things, including storing different class types in a single pointer variable, but you should truly understand what you are doing. If inheriting from a base class won't work, then I'd be very careful going about this solution.
[/quote]
I think you misunderstood... the OP wasn't talking about storing an object in a pointer (which you can do, and the object can be of various types), but instead storing a class type in a pointer (which you [i]cannot[/i] do). brx is correct.

Share this post


Link to post
Share on other sites
[quote name='fotogames' timestamp='1341563419' post='4956256']
Thanks for the responses! I'm trying to make some kind of state machine, and I wanted to be able to tell the machine which class the state machine had to make (sounds weird but my english vocab is not broad enough to explain it clearer than this [img]http://public.gamedev.net//public/style_emoticons/default/tongue.png[/img]) However I've been thinking and I don't think I need an infinite state machine, so I'm going to go with a finite state machine. Thanks for the help guys [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
[/quote]

Take a look at [url="http://en.wikipedia.org/wiki/Design_Patterns"]Design Patterns[/url]. In particular the [url="http://en.wikipedia.org/wiki/State_pattern"]State[/url] and [url="http://en.wikipedia.org/wiki/Strategy_pattern"]Strategy[/url] pattern. This might help you to work out a solution. I often find the [url="http://en.wikipedia.org/wiki/Flyweight_pattern"]flyweight[/url] pattern useful for state machines.

Share this post


Link to post
Share on other sites
[quote name='fotogames' timestamp='1341559556' post='4956241']
Kinda like this... I guess the two classes (myClass1 & myClass2) need to inherit the same class or something like that. Is this possible? Is it very complicated? If it is just say so [img]http://public.gamedev.net//public/style_emoticons/default/tongue.png[/img] I guess this is a really weird way of accomplishing what I want and I don't really need this so if it isn't possible or very hard it doesn't matter, I guess i'm still a beginner
[/quote]
Yes it's possible, yes they need to inherit the same base class. No, it's not very complicated, but yes it may be somewhat more advanced than your current level. Note that that doesn't mean to shirk back, but rather that you should stick your head down and plow stubbornly forward when you encounter problems, by keep asking questions until you understand it. ("Above your level" means, "Get out your climbing gear", not "Go do something else"). ([size=1]If i[/size][size=2][size=1]t's[/size] too confusing, that may just be because you haven't yet learned some other concepts that this is built upon, and that you should learn those first, but to mark this concept as one to look forward to learning later[/size])

If you have a base class, [i]MyBase[/i], and two classes that inherit it, [i]DerivedA [/i]and [i]DerivedB[/i], a [i]MyBase [/i]pointer or reference can actually point to a [i]DerivedA[/i] and [i]DerivedB [/i]- Or actually, they can only point to the [i]MyBase [/i]inherited part of [i]DerivedA [/i]and [i]DerivedB [/i](Since[i] DerivedA [/i]and [i]DerivedB[/i] contain[i] MyBase [/i]in it, since they inherited it), but not point at [i]DerivedA [/i]and [i]DerivedB [/i]themselves.

What good is that, then? Well, if [i]MyBase [/i]has a virtual function, let's call it [i]MyVirtualFunc[/i](), and DerivedA and DerivedB overload that virtual function with their own [i]MyVirtualFunc[/i]() (taking the exact same parameters and etc...), when you call the "[i]MyBase pointer to DerivedA[/i]" MyVirtualFunc() function, it'll actually call [i]DerivedA[/i]'s overload of it. This is because the function is [i]virtual[/i], and won't behave the same way if it's non-virtual. This only works because DerivedA and DerivedB both inherit MyBase.

Here's an example of that:
[code]class MyBase
{
public:
virtual void MyVirtualFunc() { std::cout << "MyBase::MyVirtualFunc() was called." << std::endl;}
};


class DerivedA : public MyBase
{
public:
void MyVirtualFunc() { std::cout << "DerivedA::MyVirtualFunc() was called." << std::endl;}
};


class DerivedB : public MyBase
{
public:
void MyVirtualFunc() { std::cout << "DerivedB::MyVirtualFunc() was called." << std::endl;}
};

int main()
{
MyBase myBase;
DerivedA derivedA;
DerivedB derivedB;

MyBase *myBasePtr = &myBase; //Use a MyBase pointer to point to a MyBase.
myBasePtr->MyVirtualFunc(); //Uses MyBase's version.

myBasePtr = &derivedA; //Use a MyBase pointer to point to the 'MyBase' inherited part of the DerivedA.
myBasePtr->MyVirtualFunc(); //Uses DerivedA's version.


myBasePtr = &derivedB; //Use a MyBase pointer to point to the 'MyBase' inherited part of the DerivedB.
myBasePtr->MyVirtualFunc(); //Uses DerivedB's version.

std::vector<MyBase*> myArray; //Array of multiple different class types of the same base class.
myArray.push_back(&myBase);
myArray.push_back(&derivedA);
myArray.push_back(&derivedB);

for(int i = 0; i < myArray.size(); i++)
{
myArray[i]->MyVirtualFunc();
}

return 0;
}
[/code]

Don't abuse it, but learn it, and when it seems to be the best solution for that particular case, use it. It's just another tool in your toolbox, but don't use it for every situation you encounter.
For general guidelines: [[url="http://en.wikipedia.org/wiki/Single_responsibility_principle"]Single Responsibillity Principle[/url]] [[url="http://en.wikipedia.org/wiki/Is-a"]Is-a[/url] vs [url="http://en.wikipedia.org/wiki/Has-a"]Has-a[/url]]
Also: [[url="http://www.parashift.com/c++-faq/basics-of-inheritance.html"]Inheritance - Basics[/url]] and [[url="http://www.parashift.com/c++-faq/virtual-functions.html"]Inheritance - Virtual functions[/url]], and [url="http://www.parashift.com/c++-faq/"]all the rest of that site[/url]. Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
[quote name='Servant of the Lord' timestamp='1341596409' post='4956392']
Yes it's possible, yes they need to inherit the same base class.
[/quote]
Sorry, but while everything (except, when looking at the original question, the quoted part) you wrote is correct, the original question was
[quote name='fotogames' timestamp='1341559556' post='4956241']
I'm looking for a feature where you can make a variable contain a class type.
[/quote]
and that is simply not possible in C++.

Share this post


Link to post
Share on other sites
Ah, good catch - I had figured that the original poster was just phrasing things poorly from confusion.

([size=2]Note: I had previously rated down your initial post because I [u]thought[/u] you were needlessly nitpicking technical terms in a troll-like manner (and in the For Beginner's forum too!).[/size]
[size=2]Since I now realize that you weren't trolling, but cannot undo the negative rating, I rated up your most recent post to compensate. My mistake![/size]) Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
Didn't mean to nitpick (and certainly not to troll!). But distinguishing between the terms "object" and "class" was absolutely necessary in this case, even though it is the For Beginner's forum (which, btw, I didn't even realize because I mainly use the "New Content" button)

Share this post


Link to post
Share on other sites
OK I've never been that verbally talented and indeed there's a distinction between class and object (instance of class)
Not sure then what op meant or how my post was wrong but oh well,semantics...
I suppose it would be more correct to say that if OP wants a pointer to a derived instance of a base class then it is possible or is my human language wrong again lol?

Share this post


Link to post
Share on other sites
Wow, thanks for all the useful replies! From what I read I conclude that brx is right (after all), sorry for the late reply :P I will read the wikipedia article on Design Patterns, looks very useful :D This is a really awesome forum haha, thanks :D

Share this post


Link to post
Share on other sites
You can store types and even perform operations on them (e.g., evaluate conditional expressions where types are given as arguments and types are returned as results) at compile-time using template metaprogramming.
Here in particular, you can use a so-called "instance_of_type" hollow type ("hollow types" -- ones that carry no data, in particular: no data members; I'm using "instance_of_type" term (altthough the book uses "instance_of"), to avoid confusion with the word "instance" you might've heard in OOP ("instance_of_type" is NOT an instance of a class)):
[source lang="cpp"]template &lt;typename T&gt;
struct instance_of_type
{
typedef T type;
};[/source]
For an example, see: [url="http://ideone.com/Hyi5H"]http://ideone.com/Hyi5H[/url]
Here "typeif<(sizeof(int) > 4), int, double>::type" returns type "int" if "(sizeof(int) > 4)" is true -- otherwise, it returns type "double".
Note that "typeif" itself is implemented in terms of "instance_of_type",
// There are more examples in this book: [url="http://acppmp.blogspot.com/"]http://acppmp.blogspot.com/[/url]

However, if you want to make a decision based on run-time input (e.g., from the user) -- and it sounds to me that you possibly might -- then take note it won't be suited to your problem, as compile-time is usually quite over by that time ;-)

// EDIT #4390239: OK, code editor hates templates [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img] Edited by Matt-D

Share this post


Link to post
Share on other sites
The closest C++ has to a pointer to a class type is the std::type_info class, which you can obtain from the typeid operator. However, you can't use it to instantiate objects of the type. You can use it as the basis of a factory that you implement yourself. Whether that is actually useful depends on what exactly you are trying to accomplish.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this