Search code examples
c++constructordefault-value

If a class contains object of another class can it be initialized by having default value in the constructor of containing class in C++?


Compiling this code produces the error

error time constructor time::time(int,int,char) cannot be overloaded with time::time(int,int,char)

I'm trying to reduce overloaded constructors so I am trying to give default values in the constructor parameters. Is the line entry(int sno=5,time t{1,2,'p'}); in the constructor for the entry class valid? If a class contains a complex object of another class then can it be initialized this way?

#include<iostream>

using namespace std;


class time
{
    int hours;
    int mins;
    char ap;
    
public:
    time(int hours=0,int mins=0,char ap='n');
    time(int a, int b, char c): hours{a},mins{b},ap{c}
    {
    }
    
    void showtime()
    {
        cout<<"\nTime : "<<hours<<" "<<mins<<" "<<ap<<endl;
    }
};

class entry{
    int sno;
    time t;
    public:
        entry(int sno=5,time t{1,2,'p'});
        void showdata()
        {
            cout<<"\ne : "<<sno<<" : ";
            t.showtime();
        }
        
};


int main()
{
    entry e;
    e.showdata();
    return 0;
}

Solution

  • Yes it's possible, this is just about syntax :

    #include<iostream>
    
    using namespace std;
    
    class Time
    {
        int _hours;
        int _mins;
        char _ap;
        
    public:
        Time(int hours=0,int mins=0,char ap='n'): _hours(hours),_mins(mins),_ap(ap)
        {};
        
        void showtime()
        {
            cout<<"\nTime : "<< _hours << " " << _mins << " " << _ap << endl;
        }
    };
    
    class entry{
        int _sno;
        Time _t;
        public:
            entry(int sno=5,Time t = Time(1,2,'p')):
            _t(t), _sno(sno)
            {};
            void showdata()
            {
                cout<<"\ne : "<< _sno<<" : ";
                _t.showtime();
            }
            
    };
    
    
    int main()
    {
        entry e;
        e.showdata();
        Time t2(5,2,'a');
        entry e2(3, t2);
        e2.showdata();
        return 0;
    }