Thread: Calling a constructor on a non-pointer after its declaration.

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    100

    Calling a constructor on a non-pointer after its declaration.

    Hello. let's say I have the following class:

    Code:
    class A
    {
    public:
         A(int x) :x(x) {}
    
    private:
         int x;
    };
    Now let's say I also have the following class:

    Code:
    class B
    {
         public:
         B();
    
         private:
         A a;
    };
    
    B::B()
    {
        a.A(5); // invalid
    }
    How do I fix that call to A's constructor without changing a to a pointer or something?

  2. #2
    Registered User
    Join Date
    Jul 2008
    Posts
    38
    The same way as you initialize x in class A.

    Code:
    B::B() : a(5)

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    100
    In the program I'm making right now though, I'm having to initialize a in something other than B's constructor though. kind of like this:

    Code:
    class B
    {
    public:
         void run();
    
    private:
         A a;
    };
    
    void B::run()
    {
         a.A(5); // invalid
    }

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    By the time the B object is constructed, its A member variable has been constructed, so it is too late to initialise it. You must either provide A with a default constructor, or initialise A with some default int value, and then later change it.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    May 2006
    Posts
    100
    Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 02-21-2011, 02:19 AM
  2. Replies: 10
    Last Post: 06-02-2008, 08:09 AM
  3. Constructor calling another constructor
    By renanmzmendes in forum C++ Programming
    Replies: 4
    Last Post: 03-21-2008, 03:51 PM
  4. Constructor calling another constructor?
    By cpjust in forum C++ Programming
    Replies: 10
    Last Post: 02-11-2008, 02:01 PM
  5. Calling Default Constructor
    By Davros in forum C++ Programming
    Replies: 2
    Last Post: 09-13-2004, 01:08 AM