Ali Kartal
Ali Kartal

Reputation: 25

No definition in cpp composition when I define in function

#include <iostream>

using namespace std;

class Date{

private:
    int day;
    int month;
    int year;

public:
    Date(int dy,int mt,int yr){
        day=dy;
        month=mt;
        year=yr;
    }
    void showDate(){
    cout<<day<<"/"<<month<<"/"<<year<<endl;
    }

};

class Human{
private:
    string name;
    Date birthDay;
public:
    Human(string nm,Date bd):name(nm),birthDay(bd){};

    showHumanInfo(){
        cout<<"The person named : "<<name<<" was born : ";
        birthDay.showDate();
    }

};

int main()
{
    Date birthday(1,2,1995);
    Human h1("alek",birthday);
    h1.showHumanInfo();
    return 0;
}

This works, but why it doesn't work when I do the following?

#include <iostream>

using namespace std;

class Date{

private:
    int day;
    int month;
    int year;

public:
    Date(int dy,int mt,int yr){
        day=dy;
        month=mt;
        year=yr;
    }
    void showDate(){
    cout<<day<<"/"<<month<<"/"<<year<<endl;
    }

};

class Human{
private:
    string name;
    Date birthDay;
public:
    Human(string nm,Date bd){
        name = nm;
        birthDay = bd;
        }

    showHumanInfo(){
        cout<<"The person named : "<<name<<" was born : ";
        birthDay.showDate();
    }

};

int main()
{
    Date birthday(1,2,1995);
    Human h1("alek",birthday);
    h1.showHumanInfo();
    return 0;
}

I have problem like that. Why can't I use date class in a human class?

When I change human public class like that

public:
human(){
 //  ...
}

It not working it thing is the same think but not adding date class in human class.

Upvotes: 0

Views: 103

Answers (2)

Oguzhan
Oguzhan

Reputation: 255

I think problems comes from "birthday = bd;"

It has been a while since the last time I coded in C++ but if I am not wrong, using constructor initialiser and using equal operator are not the same.

You should override "=" operator to use it with your object.

About his

Upvotes: 0

cigien
cigien

Reputation: 60228

In the definition of a constructor, all member variables must be initialized before the body of the constructor is executed. Since Date doesn't have a default constructor, there is no way to initialize it

Human(string nm, Date bd)
{  // birthDay must be initialized before this point
   // ...
   birthDay = bd; // this is assignment, which is too late
}

The fix is to either give Date a default constructor, if that makes sense, or to initialize birthDay in a member initializer list, as you did in the first example code.

Upvotes: 2

Related Questions