C ++ virtual function

Posted by user2950788 on Stack Overflow See other posts from Stack Overflow or by user2950788
Published on 2013-11-03T21:46:30Z Indexed on 2013/11/03 21:54 UTC
Read the original article Hit count: 171

masters of C++.

I am trying to implement polymorphism in C++. I want to write a base class with a virtual function and then redefine that function in the child class. then demonstrate dynamic binding in my driver program. But I just couldn't get it to work.

I know how to do it in C#, so I figured that I might have made some syntactical mistakes where I had used C#'s syntax in my C++ code, but these mistakes are not obvious to me at all. So I'd greatly appreciate it if you would correct my mistakes.

class polyTest
{
 public:
  polyTest();

  virtual void type();

  virtual ~polyTest();
};

void polyTest::type()
{
 cout << "first gen";
}


class polyChild: public polyTest
{
 public:
  void type();
};


void polyChild::type() 
{
  cout << "second gen";
}


int main()
{
  polyChild * ptr1;
  polyChild * ptr2;

  ptr1 = new polyTest();
  ptr2 = new polyChild();

  ptr1 -> type();
  ptr2 -> type();
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about polymorphism