I have two classes, namely "A" and "B". I want to store pointer of an A object inside a B object and call members of A object from B object.
Here is my code:
main.cpp:
#include <iostream>
#include "A.h"
#include "B.h"
using namespace std;
int main()
{
int num = 10;
int dbl_num;
A * my_a;
B * my_b;
b->setA(my_a);
dbl_num = b->callMemberOfAObject(num);
cout << "num : " << num << endl;
cout << "dbld_num : " << dbl_num << endl << endl;
system("pause");
return 0;
}
A.h:
#ifndef _A_H_
#define _A_H_
#include "B.h"
class A
{
public:
int multiplyByTwo(int num)
{
int ret;
ret = 2 * num;
return ret;
}
};
#endif
B.h:
#ifndef _B_H_
#define _B_H_
#include "A.h"
class B
{
private:
A * a;
public:
int callMemberOfAObject(int num)
{
int ret;
ret = a->multiplyByTwo(num);
return ret;
}
void setA(A * a)
{
this->a = a;
}
};
#endif
When I build this code, compiler gives the following error messages:
Quote:| B.h|9|error: ISO C++ forbids declaration of `A' with no type|
B.h|9|error: expected `;' before '*' token|
B.h|17|error: `A' has not been declared|
B.h|18|error: ISO C++ forbids declaration of `a' with no type|
B.h||In member function `int B::callMemberOfAObject(int)':|
B.h|14|error: `a' was not declared in this scope|
B.h|14|warning: unused variable 'a'|
B.h||In member function `void B::setA(int*)':|
B.h|19|error: 'class B' has no member named 'a'|
main.cpp||In function `int main()':|
main.cpp|14|error: `b' was not declared in this scope|
main.cpp|13|warning: unused variable 'my_b'|
||=== Build finished: 7 errors, 2 warnings ===| |
********************
HOWEVER,
I don't get any error message and everything works fine when I run the following single-file code:
#include <iostream>
using namespace std;
class A
{
public:
int multiplyByTwo(int num)
{
int ret;
ret = 2 * num;
return ret;
}
};
class B
{
private:
A * a;
public:
int callMemberOfAObject(int num)
{
int ret;
ret = a->multiplyByTwo(num);
return ret;
}
void setA(A * a)
{
this->a = a;
}
};
int main()
{
int num = 10;
int dbl_num;
A * my_a;
B * my_b;
my_b->setA(my_a);
dbl_num = my_b->callMemberOfAObject(num);
cout << "num : " << num << endl;
cout << "dbld_num : " << dbl_num << endl << endl;
system("pause");
return 0;
}
Can anyone tell me, why the multi-file version of my code does not work, while single-file version works without any error messages, nor even any warning?
I'm working on a project with lots of code, so I have to divide my code into files. I need a solution for this. Any help will be appreciated.
(IDE: Tried with both Visual Studio 2005 and Code::Blocks. They give the same kind of error messages.)