Jump to content
  • Advertisement
Sign in to follow this  
Genjix

Inheritance+Constructor woes

This topic is 5042 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

consider ...

#include <stdio.h>

class B
{
    public:
	B()
	{
		puts("B::B()");
		Method();
	}
	~B()
	{
	}

	void Foo()
	{
		puts("B::Foo()");
		Method();
	}

	virtual void Method()
	{
		puts("B::Method()");
	}
};

class A : public B
{
    public:
	A() : B()
	{
		puts("A::A()");
	}
	~A()
	{
	}

	void Method()
	{
		puts("A::Method()");
	}
};

int main()
{
	A k;
	k.Foo();

	return 0;
}


Now what is happening here is when A's constructor is called, it calls B's constructor which calls virtual Method().

When you call Foo (function from B) it again calls Method

the problem is, how come the constructor ALWAYS accesses the virtual method when the latter class overrides it, yet foo doesnt (when called from main... if called in constructor it again calls the overriden function)?

Share this post


Link to post
Share on other sites
Advertisement
What is happening is when u call the constructor for A, the constructor, before constructing anything itself, calls the constructor in B. Then as u are acting inside B, it calls the virtual method. This would be like calling any other method that belongs to the same class as where u are calling it from.

I might be able to help more if you can tell me what you are trying to achieve. Then i might be able to tell you where you are going wrong.

ace

Share this post


Link to post
Share on other sites
I think (ie not sure about it but it seems logical) :
When B::B() is called, the object is initialized with everything from B, including the virtual table. Thus, inside B::B the object essentially IS a B. Only after B::B returns does the object get intialized as it truly is (of class A) so only after A::A runs does it actually become an object of class A.

Share this post


Link to post
Share on other sites
so basically because vtable is set up from within B, and Method hasnt been overriden yet, i need to make a second (fake) constructor, which I call from A::A(), or is there a better way?

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!