Calling derived class overriden function from parent. C++ -
i have parent class p, derived class d, , function show() in both of them. also, have array of p objects, , in array assigning objects derived p, d. , i'm calling show() function array. seems calls 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 here !! } return 0; }
this because didn't declare array array of p pointers. make sure array declared like:
p* elements[ n ];
here example code 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; ( std::size_t i( 0 ); < n; ++i ) elements[ ]->func(); std::cout << "enter character exit: "; char c; std::cin >> c; return 0; }
using std::vector:
#include <iostream> #include <cstddef> #include <vector> ... // same p , d definitions in previous example. int main() { std::vector<p*> elements; elements.push_back( &p() ); // &p(): create instance of p , return address. elements.push_back( &d() ); // &d(): create instance of d , return address. ( std::vector<p*>::size_type i( 0 ), sz( elements.size() ); < sz; ++i ) elements[ ]->func(); std::cout << "enter character exit: "; char c; std::cin >> c; return 0; }
Comments
Post a Comment