#include<iostream>
#include<conio.h>
using namespace std;
class base{
public:
	base() {
	
	cout<<"base constructor"<<endl;
	getch();
	}
 virtual void out()
 {
 cout<<"I AM BASE"<<endl;
 getch();
 }


};
class derived : public base
{
public:
	derived(){
	
	cout<<"derived constructor"<<endl;
	getch();
	}
	void out(){
	
	cout<<"I am derived"<<endl;
	getch();
	}


};
int main(){
base b,*bp;
derived d;
bp=&b;
bp->base::out();//works fine
bp=&d;
bp->out();//prints i am derived whereas it should print i am base
//bp->derived::out();//error 'derived is not a base of 'base'


	
	 

return 0;


}

when the base pointer points to derived object it prints i am derived.
I am using Dev c++.

Recommended Answers

All 4 Replies

when the base pointer points to derived object it prints i am derived

This is exactly what it's supposed to do.

Take a look at this:

#include <iostream>
#include <vector>
using namespace std;

struct Fruit
{
    virtual void Speak() {}
    virtual ~Fruit() {}
};

struct Apple : Fruit
{
    void Speak()
    {
        cout << "Hi! I'm an apple!\n" << endl;
    }
};

struct Pear : Fruit
{
    void Speak()
    {
        cout << "Hi! I'm a pear!\n" << endl;
    }
};

struct AnnoyingOrange : Fruit
{
    void Speak()
    {
        cout << "( http://www.youtube.com/user/realannoyingorange )\n";
        cout << "Hey Cabbage, know why you're so smart?\n";
        cout << "'Cause you have a big head. :D\n" << endl;
    }
};

template <class T>
void cleanup(vector<T*> v)
{
    for (unsigned i=0; i<v.size(); i++) delete v[i];
}

int main()
{
    vector<Fruit*> fruits;

    fruits.push_back(new Apple);
    fruits.push_back(new Pear);
    fruits.push_back(new AnnoyingOrange);

    fruits[0]->Speak();
    fruits[1]->Speak();
    fruits[2]->Speak();

    cleanup(fruits);

    cout << "hit enter to quit..." << endl;
    cin.get();
    return 0;
}

Also, take a look at this -> http://cplusplus.com/doc/tutorial/polymorphism/

but then why the code at line 42 fails to compile because the "I am derived" belongs to derived class.
How can it use the function implicitly but not explicitly.

How can it use the function implicitly but not explicitly.

It can because the choice of the function to call isn't taken during compilation but while the program
is executed. Take a look at this here to see how -> http://en.wikipedia.org/wiki/Virtual_method_table

Also, note that this works ok:

//...

int main()
{
    derived d, *dp;

    dp = &d;
    dp->out();
    dp->base::out();

    return 0;
}

Well this clears it up thanks a bunch mate.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.