classes within classes

This is a discussion on classes within classes within the C++ Programming forums, part of the General Programming Boards category; It seems that in my time away from C++, I've forgotten something that I should still know. I have this ...

  1. #1
    Pursuing knowledge confuted's Avatar
    Join Date
    Jun 2002
    Posts
    1,916

    classes within classes

    It seems that in my time away from C++, I've forgotten something that I should still know.

    I have this class:
    Code:
    class cIPAddress
    {
    	public:
    		cIPAddress(string IPAddress) {	IP=IPAddress; }
            private:
    		string IP;
    };
    And I want to use it as a member of another class, calling the constructor for cIPAddress from within the constructor for the other class:

    Code:
    class cOtherClass
    {
    	public:
    		cIPAddress ipaddress;
                    cOtherClass(string ip){ipaddress(ip);}
    };
    Obviously, the code in the constructor cOtherClass is not the way to do it; what is?
    Away.

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    You have to use an initializer list
    Code:
    class cOtherClass
    {
      public:
        cIPAddress ipaddress;
        cOtherClass(const string& ip)
          : ipaddress(ip)
        {}
    };

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    In fact, you should use the initializer list in both cases:
    Code:
    class cIPAddress
    {
      public:
        cIPAddress(const string& IPAddress)
          : IP(IPAddress)
        {}
      private:
        string IP;
    };

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you Initialize all classes once with New?
    By peacerosetx in forum C++ Programming
    Replies: 12
    Last Post: 07-02-2008, 10:47 AM
  2. Multiple Inheritance - Size of Classes?
    By Zeusbwr in forum C++ Programming
    Replies: 10
    Last Post: 11-26-2004, 08:04 AM
  3. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM
  4. Exporting VC++ classes for use with VB
    By Helix in forum Windows Programming
    Replies: 2
    Last Post: 12-29-2003, 04:38 PM
  5. include question
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 10-17-2003, 03:49 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21