Jump to content
  • Advertisement
Sign in to follow this  

C++ question

This topic is 4335 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I was checking some things out and stumbled upon this. Look at class B how member a is declared, when u write it like this, the compiler asks to initialize it in the constructor initializer list. So I did and it compiles, but of course this doesn't look very right and it will crash, altho the destructor of A doesn't get called when u init in the initializer list. So I was wondering if this has any use at all?
#include <iostream>

using namespace std;

class A
{
public:
	virtual ~A() 
	{ 
		cout<<"A destructor call\n";
	}

	virtual void test()
	{
		cout<<"test A\n";
	}
};

class A1 : public A
{
public:
	virtual ~A1() 
	{ 
		cout<<"A1 destructor call\n";
	}

	virtual void test()
	{
		cout<<"test A1\n";
	}
};


class B
{
public:
	B() : a(A1()) //destructor wont be called
	{
		//a = A1(); //destructor will be called
	}

	A &a;
};


int main()
{
	B b = B();

	b.a.test();
	b.a.test();
	return 0;
}

Share this post


Link to post
Share on other sites
Advertisement
You are trying to bind a temporary to a reference member variable. This is not kosher. The temporary will die after construction of the class gets done with and so bad things happen when you try using the reference. You probably want a (smart) pointer member variable instead of a reference so that you can control the lifetime of the A object.

Share this post


Link to post
Share on other sites
yea i just found it weird my compiler tells me to initialize it in the right place but then not being able to work with it. just making sure if theres something I dont know about :)

Share this post


Link to post
Share on other sites
If you initialize it with a reference to something other than a temporary, like a stack variable that will outlive the B object or a global, then it will work fine. Again the problem is you are trying to initialize a reference with a temporary.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!