Pointer to class type?

Started by
17 comments, last by SiCrane 11 years, 9 months ago

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 tongue.png 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

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=2][size=1]t's 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)

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

What good is that, then? Well, if MyBase has a virtual function, let's call it MyVirtualFunc(), and DerivedA and DerivedB overload that virtual function with their own MyVirtualFunc() (taking the exact same parameters and etc...), when you call the "MyBase pointer to DerivedA" MyVirtualFunc() function, it'll actually call DerivedA's overload of it. This is because the function is virtual, 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:
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->MyVirtualFunc();
}

return 0;
}


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: [Single Responsibillity Principle] [Is-a vs Has-a]
Also: [Inheritance - Basics] and [Inheritance - Virtual functions], and all the rest of that site.
Advertisement
Removed, accidental repetition.
[size=2]Current project: Ephenation.
[size=2]Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

Yes it's possible, yes they need to inherit the same base class.

Sorry, but while everything (except, when looking at the original question, the quoted part) you wrote is correct, the original question was

I'm looking for a feature where you can make a variable contain a class type.

and that is simply not possible in C++.
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 thought you were needlessly nitpicking technical terms in a troll-like manner (and in the For Beginner's forum too!).
[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!)
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)
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?
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
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: http://ideone.com/Hyi5H
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: http://acppmp.blogspot.com/

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 biggrin.png
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.

This topic is closed to new replies.

Advertisement