I have a class
class player{
private:
int x;//coordinates
int y;
public:
player() {}
player(int px, int py) {
x = px;
y = py;
}
int get_x() {
return x;
}
int get_y() {
return y;
}
and a class avatar that inherit from class player:
class avatar :public player {
public:
avatar() {}
avatar (int px, int py) :player (px, py) {
cout << "Make a avatar in this coordinates" << " " << px << " " << py << endl;
}
I do
void start(avatar &av){
.
.
.
.
.
(in the end of the fuction)
cout << endl << avatar .get_x() << ", " << avatar.get_y();
}
int main()
avatar pl;
start(pl);
cout << endl << player.get_x() << ", " << player.get_y();
and the results i am getting are
6, 8(right answer)
-858993460, -858993460(after the function,wrong answer)
i dont understand why that happen. I use by reference function call(&)
There are many errors in the code you have shown.
But, the most important mistake that can cause the behavior you are experiencing is that you are default constructing an avatar object in main(), but neither of your default constructors in player or avatar are initializing the x and y data members, so they will have indeterminate values. That is why you see garbage in your output.
You need to initialize x and y, eg:
class player{
private:
int x;
int y;
public:
player() : x(0), y(0) {} // <-- HERE
...
};
Alternatively:
class player{
private:
int x;
int y;
public:
player(int px = 0, int py = 0) { // <-- HERE
x = px;
y = py;
}
...
};
Otherwise, you need to construct the avatar object in main() with initial values, eg:
int main()
avatar pl(6, 8);
...
}
Related
#include<iostream>
using namespace std;
class Nokta{
private:
int x,y;
public:
Nokta();
Nokta(int, int);
int getX();
int getY();
void setX(int);
void setY(int);
};
Nokta::Nokta(){
cout << "parametresiz kurucu cagrildi\n";
}
Nokta::Nokta(int x, int y=0){
this->x = x;
this->y = y;
cout << "parametreli kurucu cagrildi\n";
}
int Nokta::getX(){
return x;
}
int Nokta::getY(){
return y;
}
void Nokta::setX(int _x){
x=_x;
}
void Nokta::setY(int _y){
if(_y > 5)
y=_y;
else
y = 2;
}
int main(){
Nokta *ptr;
cout << ptr << " " << &ptr << " "<< ptr->getX() << endl;
return 0;
}
Nokta* ptr; A constructor function is not called when I type it, but I can print one of its variables to the screen. ptr->getX() works. I guess this value is randomly assigned, but how is it done in the background before an object is created?
Output
0x401b6b 0x61ff0c 1528349827
ptr is just a variable that should hold an address to a Nokta object. But you did not create a Nokta object for the pointer to point to.
Nokta noktaObj = Nokta(someNum, someNum)
Nokta* ptr = &noktaObj
When you don't initialize the object, and try to access data (like ptr->getX()), you're just getting whatever garbage happens to be in memory in that location.
I have an assignment from school to create pointers to different components of a class.
I don't understand how it works. Can someone help me with a simple program?
I have made the basic layout of what's needed. I don't know how to go about creating pointers.
#include <iostream>
#include <math.h>
using namespace std;
class Rectangle
{
int a,b;
public:
};
class Perimeter : public Rectangle
{
public:
int c;
void P(int a, int b)
{
c = 2 * (a + b);
cout << "This Is The Perimeter Of The Rectangle: " << c << endl;
}
};
class Area : public Rectangle
{
public:
int c;
void A(int a, int b)
{
c = a * b;
cout << "This Is The Area Of The Rectangle: " << c << endl;
}
};
class Diagonal : public Rectangle
{
public:
float c;
void D(int a, int b)
{
c = sqrt((a*a)+(b*b));
cout << "This Is The Diagonal Of Rectangle: " << c << endl;
}
};
#include<iostream>
#include<math.h>
using namespace std;
class Rectangle
{
int a,b;
public:
};
class Perimeter : public Rectangle
{
public:
int c;
void P(int a, int b)
{
c = 2 * (a + b);
cout<<"This Is The Perimeter Of The Rectangle: "<<c<<endl;
}
};
class Area : public Rectangle
{
public:
int c;
void A(int a, int b)
{
c = a * b;
cout<<"This Is The Area Of The Rectangle: "<<c<<endl;
}
};
class Diagonal : public Rectangle
{
public:
float c;
void D(int a, int b)
{
c = sqrt((a*a)+(b*b));
cout<<"This Is The Diagonal Of Rectangle: "<<c<<endl;
}
};
int main()
{
int e,f;
cout<<"Enter Length And Breadth: "<<endl;
cin>>e>>f;
/***************************************/
Perimeter p; //CREATING AN OBJECT
Perimeter *Peri; //CREATING A POINTER TO THE OBJECT
Peri=&p; //ASSIGNING ADDRESS TO THE POINTER
Peri->P(e,f); //MEMBER ACCESS USING POINTER TO AN OBJECT
/**************************************/
Area a;
int Area::*ptr=&Area::c; //CREATING A POINTER TO THE DATA MEMBER
a.*ptr = e;
a.A(e,f);
/*************************************/
Diagonal d;
void (Diagonal::*Dia)(int,int)=&Diagonal::D; //CREATING POINTER TO MEMBER FUNCTION
(d.*Dia)(e,f); //THIS IS HOW WE CALL THE MEMBER FUNCTION USING ITS POINTER
/*************************************/
return 0;
}
I believe this is what you were looking for.
there are some errors you made in the program. i didn't correct them but i am pointing them out.
though you didn't write anything(create any functions) in the parent class, creating pointer to an object of the sub-class is useless. in this case, early binding is taking place. you can go with a pure virtual function following function Over-Riding.
A pointer is a reference to an area in memory.
In the picture, foo is holds the value 1702 which is the spot in memory the string "hello" is stored. Pointers to elements in a class work the same way. Your class will occupy some part of memory and a pointer to the class member will hold the value of where the class member is in memory.
I'm not sure which type of pointer you're supposed to use for your class, but there's three different types.
Raw pointers:
These are the types similar to shown in the picture. An example would be:
int * x = 5; // Let's say 5 is stored at memory location 0x15
cout << x; // This will give 0x15
cout << *x; // This "dereferences" the pointer also known as go to that memory location and retrieve the value. This outputs 5
There are also Smart Pointers as defined here:
https://learn.microsoft.com/en-us/cpp/cpp/smart-pointers-modern-cpp?view=vs-2019
These are meant to be safer since they will be garbage collected, and prevent common dereferencing errors.
For using pointers in a class it could be as easy as:
class shape {
int * height;
int * width;
public:
void setHeight (int x) {height = &x; }
void setWidth(int x) { width = &x; }
int getHeight(){ return *height; }
int getWidth() { return *width; }
};
class square : class shape {
public getArea(int *h, int *w) {returns *h * *w; }
};
int main {
int x = 5;
int y = 6;
int * pointerX = &x; //& means this variable's memory address
int * pointerY = &y;
rect rectangle;
std::cout << rectangle.getArea(pointerX, pointerY) << std::endl;
rectangle.setHeight(7);
std::cout << "Rect height:" << rectangle.getHeight() << std::endl;
rectangle.setWidth(9);
std::cout << "Rect width:" << rectangle.getWidth() << std::endl;
rect * ptrRect = &rectangle;
std::cout << ptrRect->getArea(pointerX, pointerY) << std::endl;
ptrRect->setHeight(9);
std::cout << "ptrRect height:" << ptrRect->getHeight() << std::endl;
ptrRect->setWidth(10);
std::cout << "ptrRect width:" << ptrRect->getWidth() << std::endl;
std::cout << square.getArea(pointerX, pointerY) << std::endl;
}
This is what I need to do: Add a new data member, string color to your Point2D class and a new getter and setter function for color. Create a Point2D object and set its color. Then create a Point3D color and try to set its color. Is this setColor behavior available for a Point3D class? Why or why not?
This is my code:
#include<iostream>
#include<vector>
using namespace std;
class Point2D
{
friend class SPALops;
protected:
float x;
float y;
protected:
float getX(){
return x;
};
float getY(){
return y;
};
void setX(float xc){
x = xc;
};
void setY(float yc){
y = yc;
};
Point2D(int xcoord, int ycoord){
x = xcoord;
y = ycoord;
};
};
class Point2D : Point2D
{
friend class SPALops;
public:
Point2D(int x, int y) : Point2D(x,y){}
Point2D() : Point2D(0,0){}
float getX(){
return this->Point2D::getX();
};
float getY(){
return this->Point2D::getY();
};
void setX(float x){
this->Point2D::setX(x);
};
void setY(float y){
this->Point2D::setY(y);
};
};
class RectangleImplementation{
friend class SPALops;
protected:
Point2D ll;
Point2D ur;
RectangleImplementation(float llx, float lly, float urx, float ury){
ll.setX(llx); ll.setY(lly);
ur.setX(urx); ur.setY(ury);
}
void setLLx(float x){
ll.setX(x);
};
void setLLy(float y){
ll.setY(y);
};
void setURx(float x){
ur.setX(x);
};
void setURy(float y){
ur.setY(y);
};
float getLLx(){
return ll.getX();
};
float getLLy(){
return ll.getY();
};
float getURx(){
return ur.getX();
};
float getURy(){
return ur.getY();
};
vector<vector<float> > getPointList(){
vector<vector<float> > v(4);
vector<float> llv(2); llv[0] = ll.getX(); llv[1] = ll.getY();
v[0] = llv;
vector<float> luv(2); luv[0] = ll.getX(); luv[1] = ur.getY();
v[1] = luv;
vector<float> ruv(2); ruv[0] = ur.getX(); ruv[1] = ur.getY();
v[2] = ruv;
vector<float> rlv(2); rlv[0] = ur.getX(); rlv[1] = ll.getY();
v[3] = rlv;
return v;
};
void printPointList(){
vector<vector<float>> v = this->getPointList();
cout << "ll = " << v[0][0] << " , " << v[0][1] << endl;
cout << "lu = " << v[1][0] << " , " << v[1][1] << endl;
cout << "ru = " << v[2][0] << " , " << v[2][1] << endl;
cout << "rl = " << v[3][0] << " , " << v[3][1] << endl;
};
};
class Rectangle : RectangleImplementation{
friend class SPALops;
public:
Rectangle(Point2D &p, Point2D &q) : RectangleImplementation(p.getX(), p.getY(), q.getX(), q.getY()){};
Rectangle(float llx, float lly, float urx, float ury): RectangleImplementation(llx,lly,urx,ury){};
float getLLx(){
return this->RectangleImplementation::getLLx();
};
float getLLy(){
return this->RectangleImplementation::getLLy();
};
float getURx(){
return this->RectangleImplementation::getURx();
};
float getURy(){
return this->RectangleImplementation::getURy();
};
void setLLx(float x){
this->RectangleImplementation::setLLx(x);
};
void setLLy(float y){
this->RectangleImplementation::setLLy(y);
};
void setURx(float x){
this->RectangleImplementation::setURx(x);
};
void setURy(float y){
this->RectangleImplementation::setURx(y);
};
void printPointList(){
cout << "In rectangle: " << endl;
cout << "ll = " << ll.getX() << " , " << this->RectangleImplementation::getLLy() << endl;
cout << "ru = " << this->getURx() << " , " << this->RectangleImplementation::getURy() << endl;
};
};
class SPALops{
public:
static bool touches(Rectangle &r, Point2D &p){
vector<vector<float> > v = r.RectangleImplementation::getPointList();
if((v[0][0] == p.getX() and v[0][1] == p.getY()) or
(v[1][0] == p.getX() and v[1][1] == p.getY()) or
(v[2][0] == p.getX() and v[2][1] == p.getY()) or
(v[3][0] == p.getX() and v[3][1] == p.getY()))
{
return true;
}
else
{
return false;
}
};
};
int main(){
Point2D p(10,10);
Point2D q(15,15);
Point2D s(20,20);
Point2D t(10,12);
Rectangle r(p,q);
r.printPointList();
cout << "Do rectangle 'r' and point 'p' touch = " << SPALops::touches(r,p) << endl;
cout << "Do rectangle 'r' and point 's' touch = " << SPALops::touches(r,s) << endl;
cout << "Do rectangle 'r' and point 't' touch = " << SPALops::touches(r,t) << endl;
return 0;
}
It seems I have many errors that stop me from running succesfully. I would appreciate if I get any feedback.
Here are some issues I found in your post:
1) Duplicate classes.
You have a Point2D class first, then a 2nd Point2D class.
Maybe you wanted the 2nd class to be Point3D.
2) Public Inheritance.
Your class Point2D: Point2D is private inheritance.
You may want to use public inheritance:
class Point3D : public Point2D
3) The this-> notation not needed.
When accessing members or functions of the class, access them directly:
int getX() const
{ return x; }
4) Don't duplicate parent functions.
No need to have parent functions repeated in the child class. For example, the child class doesn't need a getX method. This is what inheritance is for -- so you don't need to duplicate methods.
5) Child constructor calls parent constructor.
Your constructor should look something like this:
Point3D(int new_x, int new_y, int new_z)
: Point2D(new_x, new_y),
z(new_z)
{ ; }
Too many other errors to discuss in one post. The above should get you started and give you patterns to apply to other classes.
I want to use polymorphism in my program but don't know why when I create
virtual void setVertices()=0;
in class CFigure i get an error
C2259: 'CRectangle': cannot instantiate abstract class (line 63 and 74)
IntelliSense: object of abstract class type "CRectangle" is not allowed:
pure virtual function "CFigure:setVertices" has no overrider (line 63 and 74)
I want also to declare:
virtual void setVertices(CFigure& fig) = 0;
I don't know at all that if I can write CFigure& fig cuz CRectangle i have:
void setVertices(CRectangle& fig)
and those two methods have different parameters.
Can someone can tell me how to help me to explain those errors and tell me how to fix my program? Code:
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
class Point2D{
int x, y;
public:
void setX(int X){ x = X; }
void setY(int Y){ y = Y; }
int getX(){ return x; }
int getY(){ return y; }
};
class CFigure :public Point2D
{
protected:
Point2D Vert[4];
public:
CFigure(){}
//virtual void setVertices(CFigure& fig) = 0;
virtual void setVertices()=0;// if I comment this line all works good
};
class CRectangle : public CFigure
{
public:
CRectangle(){}
void setVertices(CRectangle& fig)
{
//CRectangle fig;
int x1, y1, a;
cout << "Give x1, y1" << endl;
cin >> x1 >> y1;
cout << "Give a" << endl;
cin >> a;
fig.Vert[0].setX(x1);
fig.Vert[0].setY(y1);
fig.Vert[1].setX(x1 + a);
fig.Vert[1].setY(y1);
fig.Vert[2].setX(x1);
fig.Vert[2].setY(y1 + a);
fig.Vert[3].setX(x1 + a);
fig.Vert[3].setY(y1 + a);
}
void showPoints()
{
CRectangle f;
setVertices(f);
for (int i = 0; i < 4; i++)
{
cout << "P" << i << "( " << f.Vert[i].getX() << " " << f.Vert[i].getY() << " ) " << endl;
}
}
};
int main()
{
CRectangle ag;
ag.showPoints();
return 0;
}
CFigure declares setVertices() as:
virtual void setVertices()=0;
But CRectangle declares setVertices() as:
void setVertices(CRectangle& fig)
The additional parameter makes it so CRectangle::setVertices() is not overriding CFigure::setVertices(). It is overloading it instead. That is why the compiler is complaining that CRectangle is an abstract class - it really is. When you override a virtual method, the signature of the overriding method must exactly match the signature of the method that is being overridden, eg:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
class Point2D
{
int x, y;
public:
void setX(int X){ x = X; }
void setY(int Y){ y = Y; }
int getX(){ return x; }
int getY(){ return y; }
};
class CFigure : public Point2D
{
protected:
Point2D Vert[4];
public:
CFigure() {}
virtual void setVertices()=0;
};
class CRectangle : public CFigure
{
public:
CRectangle() {}
void setVertices()
{
int x1, y1, a;
cout << "Give x1, y1" << endl;
cin >> x1 >> y1;
cout << "Give a" << endl;
cin >> a;
Vert[0].setX(x1);
Vert[0].setY(y1);
Vert[1].setX(x1 + a);
Vert[1].setY(y1);
Vert[2].setX(x1);
Vert[2].setY(y1 + a);
Vert[3].setX(x1 + a);
Vert[3].setY(y1 + a);
}
void showPoints()
{
setVertices();
for (int i = 0; i < 4; i++)
{
cout << "P" << i << "( " << Vert[i].getX() << " " << Vert[i].getY() << " ) " << endl;
}
}
};
int main()
{
CRectangle ag;
ag.showPoints();
return 0;
}
When I try using a method to return a private variable, it seems the value changes from since the object was constructed. Here is my code and output.
main.cpp
#include <iostream>
#include "coordinate.h"
using namespace std;
int main()
{
Coordinate c(1, 1);
cout << c.getX() << endl;
}
coordinate.cpp
#include "coordinate.h"
#include <iostream>
using namespace std;
Coordinate::Coordinate(int x, int y)
{
x = x;
y = y;
cout << x << endl;
}
coordinate.h
#ifndef COORDINATE_H
#define COORDINATE_H
class Coordinate
{
private:
int x;
int y;
public:
Coordinate(int x, int y);
int getX() { return x; }
int getY() { return y; }
};
#endif
Your constructor is assigning to its arguments instead of the object's private fields. Use an initialization list, or explicitly qualify the assignment targets with this, or pick different argument names:
Coordinate::Coordinate(int x, int y) : x(x), y(y) {
cout << x << endl;
}
or
Coordinate::Coordinate(int x, int y) {
this->x = x;
this->y = y;
cout << x << endl;
}
or
Coordinate::Coordinate(int xVal, int yVal) {
x = xVal;
y = yVal;
cout << x << endl;
}
Within the constructor, x refers to the argument, rather than the member variable, so x = x is an assignment of the argument to itself. The member variables remain uninitialised.
You can avoid this problem by using a member-initialiser-list or by explicitly referring to the member variable through this->x.
Coordinate::Coordinate(int x, int y) : x(x), y(y)
{
cout << this->x << endl;
}
Did you try assigning the values to private member variables using this pointer like this?
Coordinate::Coordinate(int x, int y)
{
this->x = x;
this->y = y;
cout << x << endl;
}
or what you can do is to change the parameter names in constructor to avoid using this pointer
Coordinate::Coordinate(int a, int b)
{
x = a;
y = b;
cout << x << endl;
}
Try :
Coordinate::Coordinate(int x, int y)
{
this->x = x;
this->y = y;
cout << this->x << endl;
}
First time you get value of x = 1 because its value of argument 'x' that got print. but second time you got it wrong because, member variable x never get any value assigned.
The problem is with these assignments:
x = x;
y = y;
You are actually assigning the constructor parameters x and y to themselves, and not from the parameters to the object's x and y members.
Also, this line
cout << x << endl;
prints the constructor parameter x and not the object's x member.
You are hiding members x and y by using the same names as the constructor parameters' names. Referencing the names x and y without qualifying them would refer to the parameters and not the object's members.
You can solve this problem by doing something like this. In that, I prefixed the member variables with m_. You can also do some other similar techniques.
uselease replace the variable names as :
class Coordinate
{
private:
int a;
int b;
public:
Coordinate(int x, int y)
{
a = x;
b = y;
cout << x << endl;
}
int getX() { return a; }
int getY() { return b; }
};
Actually the compiler is getting confused which value of x to use, plz use some other variables in private section. Otherwise you can use this to resolve this also as:
Coordinate(int x, int y)
{
this->x = x;
this->y = y;
cout << x << endl;
}
With these code:
x = x;
y = y
you are assign x and y to themselves.
Coordinate::Coordinate(int xVal, int yVal)
{
x = xVal;
y = yVal;
cout << x << endl;
}
is okay.
the best way is:
Coordinate::Coordinate(int xVal, int yVal):x(xVal),y(yVal)
{
cout << x << endl;
}
As others have pointed out
Coordinate::Coordinate(int x, int y)
{
x = x;
y = y;
This is a condition called "shadow variables". The values "x" and "y" in the function prototype shadow the member variables, and thus "x = x" assigns the value of parameter x to the parameter x.
Compilers like GCC and Clang will warn you about this. MSVC doesn't because Microsoft's API is a bit messy and they use a hell of a lot of the symbol table :)
A widely used way to avoid this is prefixes. "m_" for "member", "g_" for "global", "s_" for "static".
class Coordinate
{
// by saying 'class' instead of 'struct',
// you declared the initial state to be "private".
int m_x;
int m_y;
...
Coordinate::Coordinate(int x, int y)
: m_x(x)
, m_y(y)
{}
Some folks take this a step further and use a prefix - or suffix - for parameter names; I picked up adding "_" from several Open Source projects I worked on.
Coordinate::Coordinate(int x_, int y_)
: m_x(x_)
, m_y(y_)
{
int x = m_x; // assign from member value
int y = y_; // assign from parameter
std::cout << x << ", " << y << std::endl;
}