Reputation: 18044
As everyone knows: It's possbile to create linkes lists with C / C++ in order to make a program dynamical. But now, I'm programming a "linked Class" in c++. My Parent-Class "GAME" should have a variable number of Elements. And each Element is a class. So I programmed this:
class GAME : public LEVEL
{ private:
ELEMENT *startPointer;
public:
GAME()
{ startPointer=NULL;
}
initGame()
{ p=aStartPointer;
while(p!=NULL);//This loop is based on a linked list, so its dynamic
{ startPointer=new ELEMENT(startPointer);
p=p->next;
}
}
}
class ELEMENT
{ private:
ELEMENT *next;
public:
ELEMENT(ELEMENT* nextPointer)
{ next=nextPointer;
}
}
My Problem: I never heard about a linked class before, and I'm not sure if I should use it.
Does professional programmers use such methods (and is it usefull?), or are there better Methods to do this?
Upvotes: 0
Views: 317
Reputation: 704
If what you're trying to do is create a container that can contain different types of object instances (ie, a non-homogeneous container), there're several approaches (which generally involve homogenizing the container). You can either set up a common base clase so that you can store handles-to-base. Another option is discriminated unions.
As the other posts mention, the container itself should probably be an STL container, unless you have a really good reason to use something else (and even then, the 'more standard', the better; homebrew is not a good idea unless it is for educational purposes only).
Upvotes: 0
Reputation: 439
Looks like you are trying to implement a linked list under a different name. A better design would be to use a list or vector as a member of your class to store the ELEMENTS
instead of having it be the basic functionality of the GAME
class.
This allows you to have a separation between container-like object and your application classes.
Upvotes: 0
Reputation: 168626
are there better Methods to do this?
Yes. Here is one:
class GAME : public LEVEL
{ private:
std::vector<ELEMENT> elements;
...
};
Use the standard library containers:
std::vector<>
.std::set<>
std::map<>
std::list<>
or std::set<>
Upvotes: 2