C++ Pointer to Object as Class member - c++

I'm trying to get two different classes to interact with eachother, for that I have in one class a pointer to an object of an other class, which is specified in the constructor.
Interaction works so far, I can change the paramters of the pointed-to object and I can see the changes, as I'm printing it on a terminal. BUT when I try to get a parameter from this object and try to print it to the terminal through the class which points to it I only get a zero value for an Int from which I know, cause of debug outputs, that it isn't zero, if called directly.
I will give you an example of the code:
Class A:
class Spieler
{
private:
int score;
Schlaeger *schlaeger;
int adc_wert;
int channel;
public:
Spieler(int x, Schlaeger &schl, int adc_wert_c=0, int channel_c=0 )
{
score=x;
schlaeger=&schl;
adc_wert=adc_wert_c;
channel=channel_c;
}
//....
void set_schl(Schlaeger &schl){ schlaeger=&schl;}
int getPosY(){ schlaeger->getSchlaeger_pos_y();}
int getPosX(){ schlaeger->getSchlaeger_pos_x();}
void setPosY(int y){ schlaeger->set_pos_y(y);}
void schlaeger_zeichen(){
schlaeger->schlaeger_zeichen();
}
void schlaeger_bewegen(){
schlaeger->schlaeger_bewegen(getADC());
}
//...
};
Class B:
class Schlaeger
{
private:
int schlaeger_pos_x;
int schlaeger_hoehe;
int schlaeger_pos_y;
public:
Schlaeger(int x=0, int h=5, int pos_y=15)
{
schlaeger_pos_x=x;
schlaeger_hoehe=h;
schlaeger_pos_y=pos_y;
}
int getSchlaeger_pos_x()
{
return schlaeger_pos_x;
}
int getSchlaeger_pos_y()
{
return schlaeger_pos_y;
}
int getSchlaeger_hoehe()
{
return schlaeger_hoehe;
}
void set_pos_y(int new_y)
{
schlaeger_pos_y=new_y;
}
};
The calls to the changing methods work, I can see the changes and I can see it in a debug output.

You're not returning the value in the getter
int getPosY(){ schlaeger->getSchlaeger_pos_y();}
should be
int getPosY(){ return schlaeger->getSchlaeger_pos_y();}

Related

Getting a value from a nested class in c++

Please I am trying to print out the value of a nested class from the private access specifier.
#include <iostream>
#include <cstdlib>
using namespace std;
class cal{
private:
int a = 0;
public:
int setNum(int m){
a = m;
}
void getNum(){
cout<<"the number is: "<<a<<endl;
}
class area{
public:
int setMan(int z){
cal obj;
obj.setNum(z);
return 1;
}
};
};
int main(){
cal::area obj2;
obj2.setMan(200);
cal obj3;
obj3.getNum();
'
return 0;
}
cal::area obj2;
obj2.setMan(200); is to set 200 to the nested class area and into the function setMan, of which setMan which pass the same value to the int setNum(int m){a = m;} this will set the value of a to "200". Then I wanted to print out the value of a but it displays 0 instead of 200.
Defining a nested class only provides a definition for a nested class. If you want to have a member of that class you have to declare it:
struct cal {
struct area {}; // class definition
area m_area; // member
};
int setMan(int z){
cal obj;
obj.setNum(z);
return 1;
}
The object obj is a temporary auto object and would be destroyed when you return from the function. By the way, "set" functions should not return values, returning 1 is confusing.
If you wish to connect objects somehow consider the composition or aggregation. For example:
// ...
class area{
public:
area(cal& obj) : obj(obj);
int setMan(int z){
obj.setNum(z);
return 1;
}
cal &obj;
};
// ...
int main(){
cal obj;
cal::area obj2(obj);
obj2.setMan(200);
obj.getNum();
return 0;
}
Anyway, that is just an artificial example, I don't see the reason you make area a nested class, the reason of setting values to cal from area, etc.

C++ : use current instance (object) in function

Greetings C++ community !
I am new to C++ i have this code example :
class Player
{
public:
int pdamage;
int phealth;
/* ... other data members and some void member functions (getName etc.) */
};
class Ennemy
{
public:
int edamage;
int ehealth;
};
**/*here i would like to use current objects parameters for calculation and return to current player instance(current player object) the health value.*/**
int playerHit(this.Player.damage,this.Enemy.ehealth)
{
ehealth = this.Ennemy.ehealth - this.Player.damage;
return ehealth;
};
int ennemyHit(this.Player.phealth,this.Enemy.edamage)
{
phealth = this.Player.phealth - this.Ennemy.edamage ;
return ehealth;
};
int main()
{
/*....*/
return 0;
}
Returning to the post question:
How i use current object parameters in a function for calculations?
/*Since i am new to stackoverflow and C++ Thanks for all advises and suggestions and critics ! */
In C++ you would pass the calles either as pointer or reference
int playerHit(const Player& player, const Ennemy& ennemy)
{
return ennemy.ehealth - player.pdamage;
};

Why do we need to use constructors for initializing values when we can also do it without them?

Please consider both the codes shown below. One uses a constructor to initialize the values and one does not.
Code#1
#include<iostream>
using namespace std;
class Rectangle
{
public:
int width;
int height;
};
int main()
{
Rectangle rect1{3,4};
cout<<"Width="<<rect1.width<<endl;
cout<<"Height="<<rect1.height<<endl;
return 0;
}
I get the output as,
Width=3
Height=4
Code#2
#include<iostream>
using namespace std;
class Rectangle
{
public:
int width;
int height;
Rectangle(int a,int b)
{
width=a;
height=b;
}
};
int main()
{
Rectangle rect1(3,4);
cout<<"Width="<<rect1.width<<endl;
cout<<"Height="<<rect1.height<<endl;
return 0;
}
I get the same output.
My question may be simple but, why bother using a constructor when I'm getting the same output in both the cases.
Thanks in advance
the answer is pretty simple, constructor initialize, other methods assign.
The difference may not seem very major, but consider this code.
#include<iostream>
using namespace std;
class Sample
{
private:
const int num;
public:
void setval(int i)
{
num = i;
}
int getVal()
{
return num;
}
};
int main()
{
Sample s;
s.setval(12);
cout<<s.getVal();
}
This code will give a compilation error saying that num is declared as const and we are trying to ASSIGN a value to num by making it equal to i.
Because const and references must be initialized just after declaration constructors do this Job by initializing them.
Also, make your class members private, it's a good practice and much more object oriented.
So the above code should be.
#include<iostream>
using namespace std;
class Sample
{
private:
const int num;
public:
Sample( int i):num(i){}
int getVal()
{
return num;
}
};
int main()
{
Sample s(12);
cout<<s.getVal();
}
For such simple data types it may well not matter, however there are many non plain-old-data types that benefit from or even require initialization to be at all useful.
Constructors have several benefits:
Constructors allow for a public API (encapsulation). In more complicated classes, internal data which the caller should not touch may need to be initialized.
class Foo
{
public:
Foo(int x) {
internal_data1 = some_computation1(x);
internal_data2 = some_computation2(x);
}
Some_Type3 some_method(int x)
{
return some_computation3(x, this->internal_data1, this->internal_data2);
}
private:
Some_Type1 internal_data1;
Some_Type2 internal_data2;
};
There are several C++ concepts involving constructors, such as DefaultConstructible and CopyConstructible. Constructors provide a common interface so generic code can instantiate objects of different types in a uniform way.
template<class T>
class Some_Generic
{
public:
Some_Generic(const T& t)
: internal_t(t) // Copy constructor used
{
// do work...
}
private:
T internal_t;
};

Call member function on object pointer

I am trying to write a simple game in C++ and currently have my Game_Window class holding an array of pointers to game objects as follows:
class Game_Window {
private:
int width;
int height;
int num_objects;
public:
char** objects;
/* The rest of the class goes here */
}
Inside my Game_Window class I want to define a function that calls the "print()" function on all objects held in the game window "objects" array as follows.
void Game_Window::print_objects() {
for (int i = 0; i < num_objects; i++) {
(objects[i])->print(); /* THE PROBLEM IS HERE */
}
}
When I compile I get the following error:
game_window.cpp:29:15: error: member reference base type 'char' is not a structure or union
(objects[i])->print();
~~~~~~~~~~~~^ ~~~~~
1 error generated.
All objects in my game have a "print()" function so I know that's not the issue. Any help would be much appreciated.
I think I figured it out. I created a class called Game_Object that all my game objects will inherit, and gave it a print() method.
class Game_Object {
private:
Location location;
public:
Game_Object();
Location *get_location() { return &location; }
void print();
};
class Diver : public Game_Object {
public:
explicit Diver(int x, int y);
};
class Game_Window {
private:
int width;
int height;
int num_objects;
public:
Game_Object** objects;
explicit Game_Window(int width, int height);
~Game_Window();
int get_width() { return width; }
int get_height() { return height; }
int get_object_count() { return num_objects; }
bool add_object(Game_Object object);
void print_objects();
};
The invocation of print() is now:
void Game_Window::print_objects() {
for (int i = 0; i < num_objects; i++) {
objects[i]->print();
}
}
I ran it and it game me no errors.
The type of Game_Window::objects is char** (pointer to pointer to char). Hence objects[i] is the ith pointer, and pointers don't have print() methods, which is why (objects[i])->print(); fails with the described error.
Perhaps you meant to use print(objects[i]); instead?

C++ calling a vector of classes' method in another class

class C {
public: void c_set(int x){ a = x; }
private: int a;
}
;
class U {
public: void load();
c_loader(int i, int x){ c[i].c_set(x); };
private: vector<C> c(20);
}
;
void U::load() {
int x;
cin >> x >> i;
c_loader(i, x)
}
I'm really confused with this one. I need to call a member function in another one but my problem is that the inside class is a vector of that classes. My code is supposed to work but the result is segfault. Presume that the function cget has definition.
The question is a bit unclear but try this to prevent segfault.
class C {
public: void cget(int a);
private: int a;
};
class U {
public: void load();
vector<C> c; // Note: c is made public in order to add elements from main
};
void U::load(unsigned x, int a) {
if (x < c.size()) // Check the size of c _before_ access
{
c[x].cget(a);
}
}
void main()
{
U u;
C c;
u.c.push_back(c);
u.load(0, 3); // Will end up calling cget
u.load(1, 3); // Will just return without calling cget
}
EDIT:
Just want to mention that the code in the question has changed a lot sinse my answer. That explains why my code looks quite different ;-)
In any case, the answer is still: Check the size of c before accessing it.