maja
maja

Reputation: 18044

Linked Class in C++?

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

Answers (3)

WeirdlyCheezy
WeirdlyCheezy

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

Jay Lindquist
Jay Lindquist

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

Robᵩ
Robᵩ

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:

  • Generally, use std::vector<>.
  • If you need uniqueness, use std::set<>
  • If you need to associate elements with keys, use std::map<>
  • If you need to insert or delete items from the container very often or very quickly, use std::list<> or std::set<>
  • There are other considerations. Consult a good book to learn how to effectively use standard containers.

Upvotes: 2

Related Questions