Class data member access

Hi,
Iam begginer in programming.I have some doubt regarding class data member accessing in another file.Follwing code showing error.Please correct me.
1
2
3
4
5
6
7
8
9
10
11
12
13
class A://file a.cpp
{
public:
int add;
int sub;

};
//file b.cpp
extern class A
void cal()
{
A::add=A::sub;
}
- add and sub are not static variables. They can be accessed only through instantiated objects of class A.
- Why do you have a colon after class A in the definition in a.cpp.
- I'm not sure whether you can declare an extern class like the way you have done. Where is your main function?
Several problems here:

1) Your class A declaration should be in a .h file, not a .cpp file.

2) No : on line 1.

3) You can't declare a class declaration as extern. File b.cpp should #include "a.h"

4) You have to instantiate A somewhere.
1
2
 
  A a;

Now, you can refer to a's public variables.
1
2
 
  a.add = a.sub;


Last edited on
Ok.Is it correct??
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
class A://file a.h
{
public:
int add;
int sub;
 A();//constrcr

};
//file main.cpp
#include "a.h"
class A *pA;
int main()
{
pA=new A();
}
A::A()//costructor
{
sub=10;
cal();
}
//file b.cpp
extern A *pA;
void cal()
{
pA->add=pA->sub;
}
Last edited on
You still have the extraneous colon on line 1.

File b.cpp also needs a #include a.h"

You have a memory leak because you never release the instance of A that you allocated at line 14.



Topic archived. No new replies allowed.