Inheritance+Constructor woes

Started by
2 comments, last by Genjix 19 years, 3 months ago

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)?

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

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.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
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?

This topic is closed to new replies.

Advertisement