11 Replies - 345 Views - Last Post: 21 May 2019 - 06:06 PM Rate Topic: -----

#1 MattC231   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 82
  • Joined: 06-April 17

Trying to print elements of an array of derived classes

Posted 19 May 2019 - 07:47 AM

Tested and code works up to this point when this function gets called

void printShapesInArray(Shapes * sArr, int size)
{
	for (int i = 0; i < size; i++)
	{
		sArr[i]->print(i);
	}
}



Doing something wrong but not sure what

The array contains multiple same/different derived class objects

This post has been edited by MattC231: 19 May 2019 - 07:49 AM

Is This A Good Question/Topic? 0
  • +

Replies To: Trying to print elements of an array of derived classes

#2 MrDaveForDays   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 18-May 19

Re: Trying to print elements of an array of derived classes

Posted 19 May 2019 - 08:00 AM

Could you post what you expect the output to be and what the output is? Is there any error?
Was This Post Helpful? 0
  • +
  • -

#3 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6931
  • View blog
  • Posts: 23,560
  • Joined: 05-May 12

Re: Trying to print elements of an array of derived classes

Posted 19 May 2019 - 08:02 AM

I'll take your statement of

Quote

Tested and code works up to this point when this function get called

to mean that the code compiles without errors or warnings, and that you are simply getting a runtime error or crash.

If so, very likely what has happened is that you have accidentally freed your array, or the elements of the array by the time you call your printShapesInArray() function. Any which way post the exact error that you are getting.

Try running your code in a debugger. Very often it will stop right at the time of the crash, and you can examine the state of your variables to determine the reason for the crash. Is the sArr pointer valid? Is what is being pointed at by sArr[i] valid?

If on the other hand you did get errors or warnings, you would tell us what those errors and warnings are by posting them here verbatim. Do not paraphrase or summarize.
Was This Post Helpful? 0
  • +
  • -

#4 MattC231   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 82
  • Joined: 06-April 17

Re: Trying to print elements of an array of derived classes

Posted 19 May 2019 - 12:35 PM

Shapes is the parent class while Circle, Square, and Rectangle are the child classes

void Shapes::print(int i)
{
    //virtual
}


void Circle::print(int i)
{
	cout << "in circle print";
	cout << "Shape " << i << "\nCircle" << endl;
	cout << "Center: (" << x << ", " << y << ")" << endl;
	cout << "Radius: " << radius << endl;
}


void Rectangle::print(int i)
{
	cout << "Shape " << i << "\nRectangle" << endl;
	cout << "Length: " << length << endl;
	cout << "Width: " << width << endl;
}


void Square::print(int i)
{
	cout << "Shape " << i << "\nSquare" << endl;
	cout << "Sides: " << side << endl;
}



Before running the debugger, I get these errors for line
sArr[i]->print(i)


Severity Code Description Project File Line Suppression State
Error (active) E0044 expression must have pointer type Assignment6 C:\Users\Mathew\source\repos\Assignment6\Assignment6\AssignmentShapes.cpp 203

Severity Code Description Project File Line Suppression State
Error C2819 type 'Shapes' does not have an overloaded member 'operator ->' Assignment6 C:\Users\Mathew\source\repos\Assignment6\Assignment6\AssignmentShapes.cpp 203

Severity Code Description Project File Line Suppression State
Error C2232 '->Shapes::print': left operand has 'class' type, use '.' Assignment6 C:\Users\Mathew\source\repos\Assignment6\Assignment6\AssignmentShapes.cpp 203


So, I commented out that function and the call to it from a previous function and created breakpoints at the return statements of each function that creates the respective shape

Circle createCircle()
{
	int x;
	int y;
	double radius;

	cout << "Input the points for the center of the circle." << endl;
	cout << "X: ";
	cin >> x;
	cout << "\n";
	cout << "Y: ";
	cin >> y;
	cout << "\n";
	cout << "Input the radius of the circle." << endl;
	cout << "Radius: ";
	cin >> radius;
	cout << "\n";

	Circle circShape(x, y, radius);
	return circShape;
}

Square createSquare()
{
	double s;

	cout << "Input a side length of the circle." << endl;
	cout << "Side: ";
	cin >> s;
	cout << "\n";

	Square squareShape(s);
	return squareShape;
}

Rectangle createRectangle()
{
	double l;
	double w;

	cout << "Input the length of the rectangle." << endl;
	cout << "Length: ";
	cin >> l;
	cout << "\n";
	cout << "Width: ";
	cin >> w;
	cout << "\n";

	Rectangle rectShape(l, w);
	return rectShape;
}



and the stored values in the created objects are correct
The question is idk if it gets stored in the Shape array.

string shapeType;
	int arraySize;
	Shapes * shapesArr;

	cout << " Welcome!!\nHow many shapes would you like to create?   ";
	cin >> arraySize;
	cout << "\n\n";
	shapesArr = new Shapes[arraySize];

	for (int i = 0; i < arraySize; i++)
	{
		shapeType = showMenu();

		if (shapeType == "sq")
		{
			shapesArr[i] = createSquare();
		}
		else
		{
			if (shapeType == "re")
			{
				shapesArr[i] = createRectangle();
			}
			else
			{
				if (shapeType == "ci")
				{
					shapesArr[i] = createCircle();
				}
			}
		}
	}


Was This Post Helpful? 0
  • +
  • -

#5 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6931
  • View blog
  • Posts: 23,560
  • Joined: 05-May 12

Re: Trying to print elements of an array of derived classes

Posted 19 May 2019 - 05:19 PM

In C++, you take advantage of polymorphism through pointers to objects. Your shapesArr needs to be declared as an array of pointers to Shapes. This will bring you to:
Shapes ** shapesArr;
:
shapesArr = new Shapes * [shapeCount];
:
for(size_t i = 0; i < shapeCount; i++)
{
    :
    shapesArr[i] = new Circle(...);
    // or
    shapesArr[i] = new Square(...);
    // or
    shapesArr[i] = new Rectangle(...);
    :
}
:
for(size_t i = 0; i < shapeCount; i++)
    delete shapesArr[i];
delete [] shapesArr;



Furthermore, presumably you are learning modern C++, so you should be using std::vector instead of allocating the array yourself. So the pseudo code above changes to:
std::vector<Shapes *> shapesVec;
:
for(size_t i = 0; i < shapeCount; i++)
{
    :
    shapesVec.push_back(new Circle(...));
    // or
    shapesVec.push_back(new Square(...));
    // or
    shapesVec.push_back(new Rectangle(...));
    :
}
:
for(auto shape : shapesVec)
    delete shape;



But even further, with modern C++, you shouldn't even be playing with raw pointers at all, but instead should be using smart pointers. So
std::vector<std::shared_ptr<Shapes>> shapesVec;
:
for(size_t i = 0; i < shapeCount; i++)
{
    :
    shapesVec.push_back(std::make_shared<Circle>(...));
    // or
    shapesVec.push_back(std::make_shared<Square>(...));
    // or
    shapesVec.push_back(std::make_shared<Rectangle>(...));
    :
}


Was This Post Helpful? 1
  • +
  • -

#6 MattC231   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 82
  • Joined: 06-April 17

Re: Trying to print elements of an array of derived classes

Posted 20 May 2019 - 01:34 PM

Unfortunately, the class I'm taking is not about modern c++

When the circle, square, and rectangle objects are created through user input

could I do this, store the user input in an array, return the array, then use the values stored in the array to create the objs?
Was This Post Helpful? 0
  • +
  • -

#7 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6931
  • View blog
  • Posts: 23,560
  • Joined: 05-May 12

Re: Trying to print elements of an array of derived classes

Posted 20 May 2019 - 01:52 PM

Yes, you can. See first chunk of code in post #5. Instead of calling new on each object type directly have your various createFoo() functions return dynamically allocated instances of the object types.
Was This Post Helpful? 1
  • +
  • -

#8 MattC231   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 82
  • Joined: 06-April 17

Re: Trying to print elements of an array of derived classes

Posted 20 May 2019 - 07:47 PM

So I edited all the createFoo() functions and am now using an array to store the user input to create the shapes, but the print function does not get executed

void printShapesInArray(Shapes sArr[], int size)
{
	Shapes temp[1];

	for (int i = 0; i < size; i++)
	{
		sArr[i] = temp[0];
		temp[0].print(i);
	}
}


This post has been edited by Skydiver: 20 May 2019 - 08:56 PM

Was This Post Helpful? 0
  • +
  • -

#9 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6931
  • View blog
  • Posts: 23,560
  • Joined: 05-May 12

Re: Trying to print elements of an array of derived classes

Posted 20 May 2019 - 09:04 PM

Your temp array contains one base Shape object instance. Based on your code for Shape::print() in post #4, that method does nothing. Why are you surprised that nothing happened?

Why are you assigning that temp object to the sArr array elements?
Was This Post Helpful? 0
  • +
  • -

#10 MattC231   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 82
  • Joined: 06-April 17

Re: Trying to print elements of an array of derived classes

Posted 20 May 2019 - 11:14 PM

Oh, yeah, I see what your saying.

I need clarification if I'm wrong, sArr is an array of shapes that contains either one of Circle, Square, or Rectangle object in each indices. If that's true, when I call the print() function, shouldn't it use the respective derived class function since Shapes print() is virtual? Or, should I write code in that function and then it would work???
Was This Post Helpful? 0
  • +
  • -

#11 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6931
  • View blog
  • Posts: 23,560
  • Joined: 05-May 12

Re: Trying to print elements of an array of derived classes

Posted 21 May 2019 - 03:39 AM

As I said in post #5, for polymorphism to work in C++, you need to use pointers (or references). In this case you want to have an array of pointers to Shape, rather than an array of Shape.
Was This Post Helpful? 0
  • +
  • -

#12 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6931
  • View blog
  • Posts: 23,560
  • Joined: 05-May 12

Re: Trying to print elements of an array of derived classes

Posted 21 May 2019 - 06:06 PM

Personally, I think that you should have declared your Shape class to be abstract. E.g.
class Shape
{
public:
    :
    // A pure virtual function here makes Shape an abstract class.
    virtual void print(int i) = 0;
    :
};



This will prevent you from instantiating an array of Shapes, but not prevent you from instantiating an array of pointers to Shapes. E.g. the following will result in a compiler error:
Shape shapeArr[10];


because Shape abstract.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1