-2

I have a parent class P, derived class D, and function show() in both of them. Also, i have an array of P objects, and in that array i am assigning objects derived from P, like D. And i'm calling show() function from array. But it seems that it calls only P empty function, not derived overriden function.

My Code:

//parent.h    

class P
{
public:
    P(){ }
    ~P(){ }

    virtual void show(){ }
};

//derived.h

#include "parent.h"

class D : public P
{
public:
    D(){ }
    ~D(){ }

    void show();
};

//derived.cpp

#include "derived.h"

void D::show()
{
    std::cout<<"Showing Derived Function\n";
}

//main.cpp

#include "derived.h"
#include <vector>

int main()
{
    vector<P> objectz;

    for(int i=0; i<8; i++)
    {
        D derp;
        objectz.insert(objectz.begin(), derp);
    }

    for(int i=0; i<8; i++)
    {
        objectz[i].show(); //Call it Here !!
    }

    return 0;
}
hakeris1010
  • 285
  • 1
  • 5
  • 12
  • 3
    And where is the code where you are actually using `show()`? – NathanOliver Apr 01 '15 at 16:35
  • Post this fragment of code, that is responsible for calling `show()`. @WojciechFrohmberg That would break the concept of polymorphism. – Mateusz Grzejek Apr 01 '15 at 16:36
  • About that array, is it e.g. `P a[N]` (or `vector

    v`)? Because then you need to read about [object slicing](http://stackoverflow.com/questions/274626/what-is-object-slicing). Please show how you use the classes, preferably you should create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us.

    – Some programmer dude Apr 01 '15 at 16:37

1 Answers1

2

This is probably because you didn't declare your array as an array of P pointers. Make sure that your array is declared something like:

P* elements[ N ];

Here is some example code to show polymorphism:

#include <iostream>
#include <cstddef>

struct P
{
    virtual void func() { std::cout << "Parent" << std::endl; }
};

struct D : P
{
    void func() override { std::cout << "Derived" << std::endl; }
};

int main()
{
    const std::size_t N( 2 );

    P* elements[ N ];

    P parent;
    D derived;

    elements[ 0 ] = &parent;
    elements[ 1 ] = &derived;

    for ( std::size_t i( 0 ); i < N; ++i )
        elements[ i ]->func();

    std::cout << "Enter a character to exit: "; char c; std::cin >> c;
    return 0;
}

Using std::vector:

#include <iostream>
#include <cstddef>
#include <vector>

... // same P and D definitions as in the previous example.

int main()
{
    std::vector<P*> elements; 

    elements.push_back( &P() ); // &P(): create an instance of P and return its address.
    elements.push_back( &D() ); // &D(): create an instance of D and return its address.

    for ( std::vector<P*>::size_type i( 0 ), sz( elements.size() ); i < sz; ++i )
        elements[ i ]->func();

    std::cout << "Enter a character to exit: "; char c; std::cin >> c;
    return 0;
}
bku_drytt
  • 3,169
  • 17
  • 19