Hi, so I finally got around to looking into OOP in c++ and I have a question about classes. So I made this simple class:

#include <iostream>
using namespace std;

class Shape {
    int xPos, yPos;
    public:
        Shape(int x, int y) {
            xPos=x;
            yPos=y;
        }
} ;

int main() {
    Shape l = new Shape(5,5);
}

When I do this, I get the following error: "Line 16: error: conversion from ‘Shape*’ to non-scalar type ‘Shape’ requested"
Now I googled the error and found that I need to call a new Shape like this:

SHape *l = new Shape(5,5);

Am I doing something wrong, because I don't recall ever having to do that for other classes I've used before? Thanks in advance.

I will answer your question but firstly you'd better use private keyword for xPos and yPos, it's absolutely identical what you have done but it is a good programming habit and make it easier to read your code for someone else.

Your problem is that when you say "Shape 1" you declare a shape but on the right handside "new Shape(5,5);" returns you a pointer to newly allocated Shape object. So you need to either use

1 -

Shape 1(5,5);                // Call the corresponding constructor

2 -

Shape *1 = new Shape(5,5);   // New allocates memory space, constructs the Shape object on that space, and returns you the adress of the newly constructed Shape object

Hi, so I finally got around to looking into OOP in c++ and I have a question about classes. So I made this simple class:

#include <iostream>
using namespace std;

class Shape {
    int xPos, yPos;
    public:
        Shape(int x, int y) {
            xPos=x;
            yPos=y;
        }
} ;

int main() {
    Shape l = new Shape(5,5);
}

When I do this, I get the following error: "Line 16: error: conversion from ‘Shape*’ to non-scalar type ‘Shape’ requested"
Now I googled the error and found that I need to call a new Shape like this:

SHape *l = new Shape(5,5);

Am I doing something wrong, because I don't recall ever having to do that for other classes I've used before? Thanks in advance.

SHape should be Shape, and when you access it's members "->" is used instead of ".". That's because only a pointer can be received when allocating from the heap with "new".

In C++ you should avoid pointers. In this example, you can just use a static object like so :

Shape s = Shape(10,10);

no need for the new operator or pointers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.