troubleshooting Question

C++ syntax; Instantiating a class with parameters; constructor run order

Avatar of deleyd
deleydFlag for United States of America asked on
16 Comments7 Solutions512 ViewsLast Modified:
I would like to have a ClassA, which holds within it an instance of ClassB. The instance of ClassB is created with a parameter. Something about the following code isn't doing what I expect.

File: ClassA.h
#pragma once
#include "ClassB.h"

class ClassA
  ClassB myClassB;
File: ClassA.cpp
#include "StdAfx.h"
#include "ClassA.h"

  myClassB = ClassB(12);

What I see happening when I test this, is ClassA.h line 10 is creating an instance of ClassB with no parameters. Then ClassA.cpp line 6 is creating another instance of ClassB with parameter 12, the ClassB constructor is called which handles the parameter 12, then when the ClassA constructor exists, the destructor for ClassB is called, indicating the class I just created is being deleted.

I'm left with myClassA pointing to my instance of ClassB created with the parameter 12, but I suspect that class has already been deleted, and there's another instance of ClassB floating around somewhere that was created with no parameters?

Or perhaps that's not what is happening and I need an explanation of what is happening.

What's the syntax for doing what I want, which is create an instance of ClassB with a parameter, and hold on to that class?
Join our community to see this answer!
Unlock 7 Answers and 16 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 7 Answers and 16 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros