0

Sorry if this was asked before, and if it was, just drop a link. I'm fairly new to C++.

I have a project that requires me to create a Twitter-like program; where each User has their own wall, homepage, friends list, inbox, etc. The problem is is that I have to turn in one .cpp file; I have to put all classes on one file. Now since C++ reads from top to bottom, I'm having an issue with creating/referencing other classes because they haven't been defined yet.

For instance, since User contains an object made from my FriendsList class, I have to put FriendsList first, but then there's an issue where I can't make an array that holds User because User hasn't been defined yet.

Sorry if this is a stupid question.

Edit: How would I go about forward declaration?

class FriendsList;
class User()
{
    FriendsList* friends;

    //constructor and other stuff
};
class FriendsList()
{
//stuff
};

Would it be like that? Sorry I'm just confused.

thatjkguy
  • 41
  • 1
  • 1
  • 3

3 Answers3

0

I think I get what your saying. It's weird that they make you put everything in one file. So what I would do. is the following.

class user{
    string url = "homepage"
    class friendList{
        user currFriend;
        user* nextFriend;
    };
    class wall{
        string status = "empty status";
    };
    class inbox{
        int number_of_messages;
    };
};

I also think this website might help. http://en.cppreference.com/w/cpp/language/nested_types

Please message or comment if this help or if it didn't

  • I was thinking about doing nested classes, but I've read that it's not preferred. I was just wondering if there was something simpler. But that is a valid option! – thatjkguy Sep 25 '15 at 01:56
0

Look up 'forward definition' to solve the problem of two classes depending on each others definition.

But...I don't think that's the solution that really solves your problem. Consider using std::list<> (or vector<> or array<> or whatever best suits your need) to hold the information you need. Look up c++ collections, and go from there

class user
{
    std::list<user&> m_Friends;
    std::list<std::string> m_Messages;
    std::list<std::string> m_Wall;
};
Russ Schultz
  • 2,545
  • 20
  • 22
  • Even if he uses a vector, doesn't he still need a forward declaration? If `User` contains `vector` and `FriendsList` contains `vector`, you still have a circular dependency. – Barmar Sep 25 '15 at 02:19
  • You don't need the class FriendsList at all. That's literally what the `list m_Friends` is. – Russ Schultz Sep 25 '15 at 02:25
  • But maybe he has other methods he wants to define for the `FriendsList` class. – Barmar Sep 25 '15 at 02:27
0

Forward declaration was the way to go for most of my issues. Thanks for the help and tips about other alternatives!

thatjkguy
  • 41
  • 1
  • 1
  • 3