Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,817 answers

573 users

How to use virtual functions and polymorphism in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

class Shape {
	double w;
	double h;
public:

	Shape() {
		w = h = 0.0;
	}

	Shape(double _w, double _h) {
		w = _w;
		h = _h;
	}
	void show() {
		cout << "w = " << w << " h =  " << h << endl;
	}
	double getw() {
		return w;
	}
	double geth() {
		return h;
	}
	void setw(double _w) {
		w = _w;
	}
	void seth(double _h) {
		h = _h;
	}
	virtual double area() {
		cout << "Error: area() is virtual not overridden ";
		return 0.0;
	}
};

class Triangle : public Shape {
public:
	Triangle(double w, double h) : Shape(w, h) { }

	double area() {
		return getw() * geth() / 2;
	}
};

class Rectangle : public Shape {
public:

	Rectangle(double w, double h) : Shape(w, h) { }

	double area() {
		return getw() * geth();
	}
};

int main() {

	Shape *shapes[3];

	shapes[0] = &Triangle(5.0, 9.0);
	shapes[1] = &Rectangle(8.0, 3.0);
	shapes[2] = &Shape(2.0, 7.0);

	for (int i = 0; i < 3; i++)
		cout << "Area = " << shapes[i]->area() << endl;

	return 0;
}


/*
run:

Area = 22.5
Area = 24
Error: area() is virtual not overridden Area = 0

*/

 



answered Mar 9, 2018 by avibootz
edited Mar 10, 2018 by avibootz

Related questions

1 answer 168 views
1 answer 151 views
1 answer 153 views
1 answer 139 views
2 answers 52 views
1 answer 186 views
...