udoyen udoyen - 3 months ago 9
C++ Question

How to include a class as a member of another class in c++

I have looked round the web and tried most of what they suggested but i still can't get my code to work. I have two classes created using

header files and .cpp files
I want to include one class in the other without using
inheritance
but i get an error.

Here is the code for the
Birthday class
:

Birthday.h:

#ifndef BIRTHDAY_H
#define BIRTHDAY_H


class Birthday
{
public:
Birthday(int m, int d, int y);
~Birthday();
void printDate();

protected:


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

#endif // BIRTHDAY_H


Birthday.cpp:

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

using namespace std;

Birthday::Birthday(int m, int d, int y):month(m), day(d), year(y)
{
//ctor
}

Birthday::~Birthday()
{
cout << "Birthday Destructor" << endl;

}

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

}


Then the class that will include a
Birthday class as a member
, Person class.

Person.h:

#ifndef PERSON_H
#define PERSON_H

#include "Birthday.h"

class Person
{
public:
Person(string n, Birthday b);
void printinfo();

protected:

private:
string name;
Birthday bd;
};

#endif // PERSON_H


Person.cpp:

#include <iostream>
#include <string>
#include "Birthday.h"
#include "Person.h"


using namespace std;

Person::Person(string n, Birthday b):name(n), bd(b)
{
//ctor

}


void Person::printinfo()
{
cout << name << endl;
bd.printDate();

}


Please note this works well when both classes are created in the same file but gives an error when used in separate header and source files.

Error messages:

Person::Person(string n, Birthday b):name(n), bd(b)
^
In file included from /home/george/codeblock-docs/Birthday/Person.cpp:4:0:
/home/george/codeblock-docs/Birthday/Person.h:6:7: error: candidates are: constexpr Person::Person(Person&&)
class Person
^
/home/george/codeblock-docs/Birthday/Person.h:6:7: error: constexpr Person::Person(const Person&)
/home/george/codeblock-docs/Birthday/Person.h:6:7: error: Person::Person()
/home/george/codeblock-docs/Birthday/Person.cpp: In member function ‘void Person::printinfo()’:
/home/george/codeblock-docs/Birthday/Person.cpp:18:13: error: ‘name’ was not declared in this scope
cout << name << endl;
^


Sorry was away didn't see the notice of hold I hope this is more explicit. This error showed on compiling the code

Answer

There is no std:: namespace specifier for string in your Person.h. You should specialize std::string:

class Person
{
    public:
        Person(std::string n, Birthday b);