MLAC
MLAC

Reputation: 129

Creating and initializing classes in C++

I'm learning to create classes in c++ and I've created a simply Point class. It somehow doesn't compile and I have no clue what went wrong. Please help.

Point.h

#ifndef POINT_H
#define POINT_H

class Point {

private:
    float x, y;

public:

    //default constructor
    Point();

    //constructor
    Point(float x, float y);

    float getX();

    float getY();

    void print();
};

#endif 

Point.cpp

#include "Point.h"

Point::Point(){
    x = 0.0;
    y = 0.0;
};

Point::Point(float x, float y){
    x = x;
    y = y;
}

float Point::getX(){
    return x;
}

float Point::getY(){
    return y;
}

void Point::print(){
cout << "hello" ;
{

main.cpp:

#include <Point.h>
#include <iostream>

int main()
{
    Point p(10.0f, 20.0f);
    p.print();
    return 0;
}

Below is the build message:

||=== Build: Debug in Point (compiler: GNU GCC Compiler) ===|
main.cpp|7|error: no matching function for call to 'Point::Point(float, float)'|
main.cpp|8|error: 'class Point' has no member named 'print'|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Upvotes: 0

Views: 82

Answers (2)

MORTAL
MORTAL

Reputation: 383

always use Constructor initialize list if possible

Point::Point()
   : x(0.f)
   , y(0.f)
{
}

Point::Point(float x, float y)
   : x(x)
   , y(y)
{
}

return const for both getX() getY()

Upvotes: 1

Paul Kienitz
Paul Kienitz

Reputation: 878

You forgot to put Point:: in front of print when defining the body. Also, the x = x in the constructor won't do anything. You need to assign to this->x, and likewise for y.

Upvotes: 3

Related Questions