0

I'm trying to declare a new shape Square and later will add a circle, to the same array Shape which is an abstract class.

I'm a bit confused since I'm not getting any errors but the program is just crashing (but works when the code is removed)

Main:

#include "Shape.h"
#include "Square.h"
#include <iostream>

using namespace std;

int main(int argc, char **argv) {   
    Shape *shapesArray[6];
    Square *s;
    s->setValues(1.0f, 2.0f, 3.0f, 4.0f);
    shapesArray[0] = s;

    printf("hello world\n");
    return 0;
}

Square.cpp:

#include "Square.h"

void Square::setValues(float w, float x, float y, float z){
    this->w = w;
    this->x = x;
    this->y = y;
    this->z = z;
}

Square.h:

#include "Shape.h"

using namespace std;

class Square: public Shape
{
    float w,x,y,z;

public:
    void setValues(float,float,float,float);
    Square();
};

Shape.cpp

#include <iostream>

using namespace std;

// Base class
class Shape {
public:
    // pure virtual function providing interface framework.
    virtual int getArea() = 0;
    Shape();

protected:
    int radius;
    float x;
    float y;
    float w;
    float z;
};
NewCoder2015
  • 47
  • 1
  • 8
  • 3
    `Square *s` is _a simple pointer_. It doesn't point to _anything_ since you never initialise it. So, calling `s->setValues` will crash. In C++ it's the programmer's job to allocate memory! – ForceBru Dec 11 '16 at 16:13
  • Thank you for providing all your code, but please in the future, indent it readably, [not like this](http://stackoverflow.com/revisions/41088191/1). – HostileFork says dont trust SE Dec 11 '16 at 16:17
  • Please also note that `using namespace std` is bad practice, and using it in a header file is extremely bad. – n. m. could be an AI Dec 11 '16 at 16:26

2 Answers2

1
Square *s;

This doesn't cause s to point to anything in particular. Using the value of s in this state is undefined behaviour. You have to initialize s before you can use it.

Normally you would initialize it like this:

Square *s = new Square;

however if you do that, you will find out that you have an unresolved reference error. Please read this question and answer about this error. Meanwhile you can just remove these lines:

Square();
Shape();

When you feel your classes need a constructor, add them back, with definitions. Note that a constructor is a vastly superior alternative to a function like setValues.

Community
  • 1
  • 1
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
0

You need to initialise a Square object by calling Square* s = new Square(); in Main at line 9. In your code, there is no object instance yet, so that you cannot call a function such as s->setValues(1.0f, 2.0f, 3.0f, 4.0f);. s here is just a pointer that points to no meaningful memory location.

dnzprmksz
  • 144
  • 1
  • 6