#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.
Related
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);
...
}
Background
I am self-learning C++ from this course, and I am unsure whether I understand why exactly my syntax was wrong.
Problem
Please see the two versions of the PointArray constructor in geometry_test.cpp. The first one gives an error, while the second one comes from the solution manual. In my (probably flawed) understanding, the two versions should be equivalent. Where have I gone wrong? When am I referring to the member attributes points and size? and when am I referring to the input variables points and size?
Thank you for any clarifications or suggestions to references I should check out.
Related query
How might the error message suggest a solution?
Code
geometry_test.h
class Point {
private:
int x, y;
public:
Point(int create_x = 0, int create_y = 0) { x = create_x; y = create_y; };
int getX() const { return x; };
int getY() const { return y; };
void setX(const int new_x) { x = new_x; };
void setY(const int new_y) { y = new_y; };
};
class PointArray {
private:
Point *points;
int size;
void resize(int n);
public:
PointArray(const Point points[], const int size);
~PointArray() { delete[] points; };
};
geometry_test.cpp
#include "geometry.h"
#include <iostream>
using std::cout;
PointArray::PointArray(const Point points[], const int size) { // breaks
points = new Point[size];
this->size = size;
for (int i = 0; i < size; ++i) { this->points[i] = points[i]; }
}
/*
PointArray::PointArray(const Point ptsToCp[], const int toCpSz) { // works
points = new Point[toCpSz];
size = toCpSz;
for (int i = 0; i < toCpSz; ++i) { points[i] = ptsToCp[i]; }
}
*/
int main() {
Point p1(1, 0);
Point p2(2, 0);
Point p3(1, 1);
Point ptarray[3] = {p1, p2, p3};
PointArray pa(ptarray, 3);
cout << p1.getX() << ", " << p1.getY() << "\n";
cout << p2.getX() << ", " << p2.getY() << "\n";
cout << p3.getX() << ", " << p3.getY() << "\n";
return 0;
}
Error message
geometry_test(17467,0x11b51adc0) malloc: *** error for object 0x7ffee4705690: pointer being freed was not allocated
geometry_test(17467,0x11b51adc0) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6
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 question already has answers here:
What is the 'this' pointer?
(8 answers)
Closed 4 years ago.
I confused what does it mean this pointer and how it is used exactly. in the below examples give the same output. What is the difference putting reference operator(&) in the setX and setY functions?
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test (int x = 0, int y = 0) { this->x = x; this->y = y; }
Test setX(int a) { x = a; return *this; }
Test setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1;
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
With reference operator
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test (int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1;
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
When you return by value, as in
Test setX(int a) { x = a; return *this; }
then you return a copy of the object. And the copy is totally unrelated to the original object.
When you return a reference, you return a reference to the actual object, no copies are made.
And because of this difference the two programs you show should not produce the same output. The first should say that x is equal to 10 (because you set x on the obj1 object) but then you set y on the copy returned by setX, meaning that obj1.y will still be zero. See e.g. this example.
When returning a reference to the object on which the function is invoked, the returned reference can be used to chain function calls on a single object.
Here, I am applying the same concept. But I am getting different output if I initialize objects differently.
First example:
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1(5, 5);
// Chained function calls. All calls modify the same object
// as the same object is returned by reference
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
Output is 10 and 20, which is correct.
However, output is not correct for the second example:
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test (int x = 0, int y = 0) { this->x = x; this->y = y; }
Test setX(int a) { x = a; return *this; }
Test setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1;
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
Output is 10 and 0.
Why? I think both are the same, the output of the second program should be 10 and 20 too. What is the reason it's different?
The difference is that the second version of your program returns by value. This means that the second call (i.e. setY) is performed on a copy of obj1, not on the obj1 itself. That's why only X ends up being set, but not Y.
In your first program, on the other hand, the setters return their results as a reference. This means that no copy is being made, so setY is called on the same object as setX, not on its copy.