-6

I have 3 classes using templates, and 2 from an abstract base class. In my main() I am applying polymorphism concepts, but from the pointer to base class, the objects of the derived class are not being initialized. I'm not sure where the problem is in my code.

#include<iostream>
#include<conio.h>
using namespace std;

template<class T>
class polygon
{
protected:
    T a,b;
public:
    virtual T area()=0
}

template<class T>
class rectangle:public polygon
{

public:
    rectangle(T c,T d)
    {
        a=c;
        b=d;
    }
    T area()
    {
        return (a*b);
    }
};

template<class T>
class triangle:public polygon
{

public:
    rectangle(T c,T d)
    {
        a=c;
        b=d;
    }
    T area()
    {
        return (.5*a*b);
    }
};

template<class T>
class rectangle
{

public:
    rectangle(T c,T d)
    {
        a=c;
        b=d;
    }
    T area()
    {
        return (a*b);
    }
};
void main (void)
{

polygon<float>*ppoly=new rectangle<float>(4,5);
cout<<ppoly->area();
getche();

}
  • Your code shouldn't even compile. Can you fix that, and explain what problems you are having? – juanchopanza May 26 '13 at 07:32
  • well basic problm is that from pointer of base class it is not initializing the object of derived class as it normally does without templates does it have anything to do with templates or i have some problm in syntax plzz ignore the execution part. that's not my concern ri8 now – Mohammad Zubair May 26 '13 at 07:39
  • No idea, because the code you posted doesn't even compile. So you are running different code. How are we supposed to know what is wrong with code you are not showing? – juanchopanza May 26 '13 at 07:40
  • well now i have added an executable part in it – Mohammad Zubair May 26 '13 at 07:50
  • Could you make this into a shorter but complete example? Also this is supposed to be a question and answer format. You haven't asked a question so that makes it difficult for people to answer. – Bull May 26 '13 at 07:53
  • What you added does not help at all. What you posted does not compile, so there is no way it does what you claim. Unless you have a very broken compiler. – juanchopanza May 26 '13 at 08:07

2 Answers2

0

The main issue is you need to inherit template class this way:

template<class T>
class rectangle : public polygon<T> // polygon is a template, you need to make
                                ^^^ // rectangle from a concrete polygon type
billz
  • 44,644
  • 9
  • 83
  • 100
0

Another thing: you have 2 definitions of rectangle class. One, that's inheriting from polygon, and one, that does not.

Kędrzu
  • 2,385
  • 13
  • 22