233k views
5 votes
Write a C++ program to define an abstract class in polymorphism?

User Vix
by
5.1k points

1 Answer

5 votes

Answer:

Following are the program to this question:

#include <iostream>//header file

using namespace std;//namespace

class Val //defining abstract class

{

public://use access specifier

virtual int squ()=0;//declaring a method squ

void setval(int x) //defining a method setval

{

a=x;//holding value in a variable

}

protected://use access specifier

int a;//defining integer variable

};

class square: public Val //defining a class square that inherit abstract class

{

public://use access specifier

int squ() //defining squ method

{

return (a*a); //return square value

}

};

int main() //main method

{

square s;//creating class object

s.setval(5);//calling setval method

cout << "The square value is: " << s.squ() << endl;//print value by calling squ method

}

Output:

The square value is: 25

Explanation:

In the above code a two-class "Val and square" is declared, in which val is abstract class, in a method squ is declared, and setval is used to set the value.

In the next step, the square class inherits Val and defines the squ method, and uses the return keyword to return its calculated value.

In the main method square class object is created and set the setval value and call the squ method and print its value.

User Ronald Luc
by
5.4k points