Reputation: 1150
Class Point is working correctly, It is creating x, y point. Code:
point.h file
#ifndef POINT_H
#define POINT_H
namespace pt
{
class Point
{
int x, y;
public:
Point();
Point(int x, int y);
int getX();
int getY();
};
}
#endif // POINT_H
point.cpp file
#include "point.h"
pt::Point::Point()
{
this->x = this->y = 0;
}
pt::Point::Point(int x, int y)
{
this->x=x;
this->y=y;
}
int pt::Point::getX()
{
return this->x;
}
int pt::Point::getY()
{
return this->y;
}
Meanwhile when I try to create new Point3D class in main that will inherit from Point x, y coordinates and add z to create third dimension, new constructor cant get access to x, y of Point class. Errors are: 1. 'int pt::Point::x' is private at first and second this-> in Point3D constr. 2. Both are 'out of context'
main.cpp
#include <iostream>
#include "point.h"
int main()
{
class Point3D : public pt::Point
{
int z;
public:
getZ()
{
return this->z;
}
Point3D(int x ,int y, int z)
{
this->x=x;
this->y=y;
this->z=z;
}
};
return 0;
}
Thanks for help.
Upvotes: 0
Views: 128
Reputation: 1322
To make x
and y
accessible to derived classes, you should make them protected:
class Point
{
protected:
int x, y;
public:
Point();
Point(int x, int y);
int getX();
int getY();
};
By default, the visibility of a class member is private
(note that this is different from the struct default where a struct member is public
by default). On that topic, see this answer.
And as a side note, the idiomatic way to initialize x
and y
would be to write:
Point3D(int x ,int y, int z) : pt::Point(x,y)
{
this->z=z;
}
Then, you don't need to make x
and y
protected, they can remain private.
You can even write it like that:
Point3D(int x ,int y, int z) : pt::Point(x,y), z(z)
{}
Upvotes: 2