C++ Programming Hi, I am having trouble calling on other functions in my print f
ID: 3794042 • Letter: C
Question
C++ Programming
Hi, I am having trouble calling on other functions in my print function. We must print a character and its position on a grid. Since there are different classes for each different character, each with the name function like below, I don't know if it affects how name() must be called.
void Shape::print(void) const
{
int i = 0;
char name = name();
int n = size();
cout << name << " ";
while (i < n)
{
cout << "(" << x[n] << "," << y[n] << ") ";
i++;
}
}
The name and size function vary depending on the letter, but for the sake of testing it out we have:
int I::size(void) const
{
return 0;
}
char I::name(void) const
{
return 'I';
}
I think it has to do with how I am calling it. I am including below part of the .h file and the main file in case it is relevant. Any help is appreciated!! Thank you!
class Shape
{
public:
virtual ~Shape(void);
virtual char name(void) const = 0;
virtual int size(void) const = 0;
void print(void) const;
void move (int dx, int dy);
bool overlap(const Shape &t) const;
static Shape *makeShape(char ch,int posx,int posy);
protected:
int *x, *y;
};
//
// testShape.cpp
//
#include "Shape.h"
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
Shape *t1, *t2;
char ch;
int x,y;
try
{
cin >> ch >> x >> y;
t1 = Shape::makeShape(ch,x,y);
t1->print();
cin >> ch >> x >> y;
t2 = Shape::makeShape(ch,x,y);
t2->print();
t2->move(1,-1);
t2->print();
if ( t1->overlap(*t2) )
cout << "overlap" << endl;
else
cout << "no overlap" << endl;
delete t1;
delete t2;
}
catch ( invalid_argument &exc )
{
cout << exc.what() << ": " << ch << " " << x << " " << y << endl;
}
}
Explanation / Answer
Ans: Hi, the way you have called other functions(namely, name() and size()) from within your print() function, is absolutely correct and there's no error in it.
The place where you are going wrong is, the way you have declared your name() and size() functions. You need a different class for each letter you are going to represent through the Shape class.
So e.g lets assume that the letter U has a class LetterU. Then inside this class you need to declare as well as define both your name() and size() methods.
ex:
class LetterU:Shape {
char name(void);
int size(void);
}
char LetterU::name()
{
//Have letter specific implementation
//of name here
}
int LetterU::size()
{
//Have letter specific implementation
//of size here
}
PS: makeShape(char ch, int posx, int posy) should return an object of the appropriate class according to the value of ch passed as a parameter to makeShape(). You can use a switch statement for the same, as I believe the number of Letters to be made are less.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.