silly little question on variable scope

B

Bit byte

What's wrong with this:

//file1.h

Class A {
public:
A(){i=1;}
~A(){;}
void doThis(void){;}
void doThat(void){;}

private:
int i;
};


//file2.h
#include "file1.h"

A a;

Class B {
public:
B(){
//a = new A(); //will not compile
//a.doThis();
}
~B(){;}
};


Anyone know why I can't use a (type A) in class B ?
 
A

Axter

Because you declared A as a concrete type instead of as a pointer.
You need a pointer to use new A()

A *a = new A;

But in general, you should avoid using pointers if you don't have to.
If you don't need to use the new operator to create an instance of an
object, than don't use it, and declare it as a concrete object instead.
 
P

Puppet_Sock

Bit said:
What's wrong with this:

//file1.h

Class A {
public:
A(){i=1;}
~A(){;}
void doThis(void){;}
void doThat(void){;}

private:
int i;
};


//file2.h
#include "file1.h"

A a;

Class B {
public:
B(){
//a = new A(); //will not compile
//a.doThis();
}
~B(){;}
};


Anyone know why I can't use a (type A) in class B ?

You can. Your problems don't arise from that.

First, you've got a variable at file scope in an h file.
You don't usually want that. If you include file1.h in
more than one .cpp file, you get trouble. If you want
an instance of class A at file scope, you need to
declare it in the .cpp file where you want it, not in
a header file.

Next, as somebody pointed out, you've got a call
to new and you are putting the result into a non-pointer.
Calls to new return pointers to allocated memory.
Read up on pointers.

Next, you are doing something pretty whack even
if you do change the variable a to a pointer, and
even if you do have only one instance of a at
file scope. You are assigning a pointer to a "newed"
instance to the variable a. But the variable a is
outside the scope of the class B that is doing it.
So, the second time you do this, you will wind
up with a resource leak.

Probably what you want is something like so. First,
drop the variable a entirely. Then add a pointer as
a member of class B. Then add the appropriate
thing to the dtor of B to avoid the memory leak.

#include "file1.h"

Class B {
public:
B(){
pa = new A(); //will not compile
pa->doThis();
}
~B(){delete pa;}
private:
A * pa;
};

Socks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top