儚き 戦士の翼
儚き 戦士の翼

Reputation: 59

New types may not be defined in a return type when creating a class

I've just started learning about OOP and classes from our school's online module and I'm running into a problem with the object provided in the module.

This is the object:

//box.h
class Box
{
    public:
    //Properties
    char Color[];
    int Length, Width, Height;

    //Methods
    Box(int length, int width, int height);
    int getVolume();
}

Box::Box(int length, int width, int height)
{
    this.Width=width;
    this.Height=height;
}

Box::getVolume()
{
return this.Length * this.Width * this.Height;
}

And this is where it's called in main()

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include "box.h"
using namespace std;

int main()
{
    Box box(2,3,4);
    cout << "The volume of our box is: ";
    cout << box.getVolume() << "." <<endl;
    cout << endl;
    system ("pause");
    return EXIT_SUCCESS;
}

Attempting to compile this gives me a whole bunch of compile errors:

Compile errors

I'm not sure where to start as this was the code provided by the module and it's Saturday night over here so the professor isn't available for questions.

Apologies if this is below the community's paygrade. I've only just started OOP and English is not my native language.

Upvotes: 2

Views: 316

Answers (2)

ic_Engineer
ic_Engineer

Reputation: 314

A lot of errors, I have cleaned your code to the following code:

class Box
{
public:
    //Properties
    char Color[10]; //imcomplete type you have to specify the length i.e. char Color[10]
    int Length, Width, Height;

    //Methods
    Box(int length, int width, int height);
    int getVolume();
};

Box::Box(int length, int width, int height)
{
    this->Width = width;
    this->Height = height;
   this->Length = length; //you have to add this line otherwise the final result will be a garbage value
}

int Box::getVolume()
{
    return this->Length * this->Width * this->Height;
}
int main()
{
    Box box(2, 3, 4);
    std::cout << "The volume of our box is: ";
    std::cout << box.getVolume() << ".\n";
    system("pause");
    return EXIT_SUCCESS;
}

Upvotes: 2

tadman
tadman

Reputation: 211570

In C++ this is a pointer to the object you're in, it is not a reference, as such you need to do:

this->x

When accessing property x. That being said, you don't even need the this part if there's no conflict with local variables or arguments, you can just x.

Or in other words:

return Length * Width * Height;

Note, when defining constructors you should steer towards constructor lists, like this:

Box::Box(int length, int width, int height) : Length(length), Width(width), Height(height)
{
}

Upvotes: 2

Related Questions