C++ only please Write a program for a graphics system that has classes for recta
ID: 3759992 • Letter: C
Question
C++ only please
Write a program for a graphics system that has classes for rectangles, squares, circles and triangles. Each of these must be derrived from a base class, Figure. You must inlcude member functions of your choice that output a message telling what function has been called and what the class of the calling object is. Create two instances within the program:
1. Do the class definitions using no virtual functions.
2. Make the base class member functions virtual.
Explain the differences in the results using virtual functions instead of no virtual functions.
Explanation / Answer
figure.h header file
#include <iostream>
using namespace std;
#ifndef PROTECT_FIGURE_H
#define PROTECT_FIGURE_H
class Figure
{
public:
virtual void erase();
virtual void draw();
void center()
{
cout << "member function center called " << endl;
erase();
draw();
}
};
void Figure::erase()
{
cout << "Figure::erase()" << endl;
}
void Figure::draw()
{
cout << "Figure::draw()" << endl;
}
#endif
rectagle.h //header file
#include <iostream>
#include "figure.h"
using namespace std;
class Rectangle : public Figure
{
public:
void erase();
void draw();
};
void Rectangle::erase()
{
cout << "Rectangle::erase() " << endl;
}
void Rectangle::draw()
{
cout << "Rectangle::draw() " << endl;
}
circle.h //header file
//circle.h
#include <iostream>
#include "figure.h"
using namespace std;
class Circle : public Figure
{
public:
void draw();
void erase();
};
void Circle::draw()
{
cout << " Circle::draw() " << endl;
}
void Circle::erase()
{
cout << " Circle::erase()" << endl;
}
triangle.h //header file
#include <iostream>
#include "figure.h"
using namespace std;
class Triangle : public Figure
{
public:
void draw();
void erase();
};
void Triangle::draw()
{
cout << "Triangle::draw() " << endl;
}
void Triangle::erase()
{
cout << "Triangle::erase()" << endl;
}
Program code:
// virtualgraphics.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "figure.h"
#include "rectangle.h"
#include "triangle.h"
#include "circle.h"
using namespace std;
int main()
{
Triangle tri;
tri.draw();
cout << " In main, Derived class Triangle object calling"
<< " center(). ";
tri.center();
Rectangle rect;
rect.draw();
cout << " In main, Derived class Rectangle object calling"
<< " center(). ";
rect.center();
Circle cir;
cir.draw();
cout << " In main, Derived class Circle object calling"
<< " center(). ";
cir.center();
system("pause");
return 0;
}
Sample output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.