Sign in to follow this  

Inheritance+Constructor woes

This topic is 4735 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 [b]Foo[b] (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
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

This topic is 4735 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this