Thread: Creating an object without default constructor

  1. #1
    Registered User
    Join Date
    May 2013
    Posts
    228

    Creating an object without default constructor

    Hi.

    I have a question about the default constructor.

    To my best understanding, the compiler will provide me with a deafult constructor only if there are no any user defined constructors, at all.

    now consider the following code:

    Code:
    class MyClass
    {
    private:
        int m_data;
    public:
        MyClass(int init):m_data(init){cout<<"Ctr called"<<endl;}
    };
    
    int main()
    {
        MyClass obj;
    }
    this code won't compile, since there is "no matching function for call to 'MyClass::MyClass()'".
    so far, everything makes sense, since there is no deafult constructor, I can't instantiate a MyClass object without providing one int parameter.

    what confusing me is that this code will compile:

    Code:
    class MyClass
    {
    private:
        int m_data;
    public:
        MyClass(int init):m_data(init){cout<<"Ctr called"<<endl;}
    };
    
    int main()
    {
        MyClass obj(); //added parentheses
    }

    How is it that suddenly, there is a default constructor?
    Last edited by Absurd; 06-24-2013 at 10:03 AM.

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    There's not suddenly a default constructor. What you've done is prototype a function named obj, that returns a MyClass and takes no arguments.

    Jim

  3. #3
    Registered User
    Join Date
    May 2013
    Posts
    228
    Thanks jimblumberg!
    that clears things up.

  4. #4
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    if you define a constructor of any kind, the compiler will not generate the default or copy constructor for you. if you define one, you have to define them all yourself.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 02-21-2011, 02:19 AM
  2. Specialized Constructor call Default Constructor
    By threahdead in forum C++ Programming
    Replies: 15
    Last Post: 08-23-2010, 03:39 PM
  3. Creating an array of object w/no default constructor
    By Angus in forum C++ Programming
    Replies: 28
    Last Post: 05-06-2009, 05:10 PM
  4. Creating array of objects w/o default constructor
    By QuestionC in forum C++ Programming
    Replies: 19
    Last Post: 05-02-2007, 08:03 PM
  5. Uninstantiated object/no default constructor available
    By patricio2626 in forum C++ Programming
    Replies: 14
    Last Post: 10-25-2006, 05:42 AM