Connell Gauld wrote:
> I have come across a problem with a slightly complicated section to a
> program I am writing.
> I have a class (let's call it ClassA) which has, in its public area, a
> variable (which happens to be another class, ClassB) like this:
>
> class ClassA
> {
> public:
> // ...
> ClassB myVar;
> // ...
All public? Any constructors? Any reference members? We may be
looking at a POD, then again we may not. Not enough information to
know for sure.
> }
>
> I have a function (doFunction) in yet another class (ClassC) which takes
> a pointer to a ClassB as a parameter. Now, the following compiles and
> works:
>
> ClassA instance1;
>
> int main()
> {
> //...
> ClassC instance2;
> instance2.doFunction(&instance1.myVar);
> //...
> }
>
> The following, however, compiles but causes an Access Violation when run:
>
> int main()
> {
> ClassA *ptrInstance1;
> ptrInstance1=new ClassA;
> ClassC instance2;
> instance2.doFunction(&ptrInstance1->myVar);
> }
>
> Is there something wrong with my code here? Is the problem in doFuntion?
The only thing that I can see here that may make a difference is that
the global object 'instance1' is filled with 0s before initialising
to whatever, but when you say
new ClassA;
the object _may_ be left uninitialised, and that means that the value
of 'myVar' is whatever came with the memory 'new' is giving you. Try
replacing it with
new ClassA();
and see if there is a difference. Otherwise, make sure you initialise
all members to something by adding a default constructor to ClassA.
> Any help would be greatly appreciated. Sorry for the horrible
> function/class names. Using VC++
VC++ or not shouldn't matter. If you, however, find that your code
works fine if compiled by another compiler, and doesn't if compiled
by VC++, then you should ask in microsoft.public.vc.language for
assistance, perhaps it's a bug. But if not, then there is no
difference what compiler you're using.
V
|