composition why is this not legal?

Hi I'm just wondering why I get an error with this code
the error is line 8 :no matching function for call to birthday::birthday()'


birthday.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  #ifndef BIRTHDAY_H
#define BIRTHDAY_H


class birthday
{
    public:
        birthday(int day,int month,int year);
        void sayBirthday();

    private:
        int d;
        int m;
        int y;
};

#endif // BIRTHDAY_H 


birthday.cpp

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

#include "birthday.h"
#include <iostream>

using namespace std;

birthday::birthday(int day,int month,int year)
{

    d = day;
    m = month;
    y = year;


}


void birthday::sayBirthday(){


    cout << d << m << y << endl;


}



person.h

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


#ifndef PERSON_H
#define PERSON_H
#include "birthday.h"

class person
{
    public:
        person();

    private:

        birthday b;
};

#endif // PERSON_H


person.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13

#include "person.h"
#include "birthday.h"
#include <iostream>


using namespace std;

person::person()
{
    //ctor
}


but when I add the following code to person.h

1
2
3
4


   person(birthday bo);


and to person.cpp

1
2
3
4
5
6
7
8
9


person::person(birthday bo)
:b(bo)
{
    //ctor
}



it works


thanks
Since you have defined a constructor for birthday, there is no default constructor.

Since class person contains an object of type birthday, and the person constructor doesn't explicitly construct the birthday object, the compiler will attempt to construct it with the default constructor. But there is none, so you get the error.

One way is to call the existing constructor in the person constructor:
1
2
3
person::person() :
    b(12,25,2000)  // construct b with birthday(int day ,int month ,int year)
    {}

Another is to add a default constructor to class birthday
1
2
3
4
5
6
7
8
9
10
11
12
class birthday
{
    public:
        birthday() : d(25), m(12), y(2000) {}
        birthday(int day,int month,int year);
        void sayBirthday();

    private:
        int d;
        int m;
        int y;
};

A third is to declare default parameters to the existing birthday constructor:
1
2
3
4
5
6
7
8
9
10
11
class birthday
{
    public:
        birthday(int day=25,int month=12,int year=2000);
        void sayBirthday();

    private:
        int d;
        int m;
        int y;
};
hey thanks for the reply still a little confused because the code

1
2
3
4
5
6
7
8

person::person(birthday bo)
:b(bo)
{
    //ctor
}



doesn't call the birthday constructor either but this works
> :b(bo)
it calls the copy constructor.
thanks guys
Topic archived. No new replies allowed.