[try Beta version]
Not logged in

 
Class Composition

Aug 14, 2013 at 11:02am
So I was experimenting with class composition on Code::Blocks, and for some reason when I compile this code I get "Lenny the Cowboy was born on 12093123/1203812038012/1203981 (some random digits), when I actually want it to be: 7/9/97. I get no errors when I run this simple program. Anyone know what I'm doing wrong?
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 #include <iostream>
#include <string>

using namespace std;

class Birthday{

public:
    Birthday(int cmonth, int cday, int cyear){
        cmonth = month;
        cday = day;
        cyear = year;

    }
    void printDate(){
        cout<<month <<"/" <<day <<"/" <<year <<endl;

    }
private:
    int month;
    int day;
    int year;

};

class People{

public:
    People(string cname, Birthday cdateOfBirth)
    :name(cname),
    dateOfBirth(cdateOfBirth)
    {

    }
    void printInfo(){
        cout<<name <<" was born on: ";
        dateOfBirth.printDate();
    }

private:
    string name;
    Birthday dateOfBirth;

};


int main() {

    Birthday birthObject(7,9,97);
    People infoObject("Lenny the Cowboy", birthObject);
    infoObject.printInfo();

}
Aug 14, 2013 at 11:13am
In lines 10 - 12, it looks as though your constructor is supposed to be setting the data members to the values passed in as parameters. In fact, you're doing exactly the opposite.
Aug 14, 2013 at 11:18am
Thanks!
Topic archived. No new replies allowed.