Sarriman
Sarriman

Reputation: 422

Pass created object as argument, from inside that object, C++

I am facing the following problem. I have the following classes, Room and Reservation . For Reservation class there is a function (void Reservation :: rsrvRoomAssignment(Room* r)) that assigns the Room* rsrvRoom member of Reservation class, to a Room object. I want though to call this class from inside the Room object but i have no clue on how to achieve that properly passing as argument the created object that runs the code.

The code describes the above:

Reservation.h

class Room;

class Reservation {
public:
    static int rsrvCode;
    string rsrvName;
    unsigned int rsrvDate;
    unsigned int rsrvNights;
    unsigned int rsrvPersons;
    Room* rsrvRoom;             // Room assigned to reservation.
    Reservation();
    ~Reservation();
    void rsrvRoomAssignment(Room*);

};

Reservation.cpp

#include <iostream>
#include "Reservation.h"

using namespace std;

/* 
    Constructor & Destructor 
*/

void Reservation :: rsrvRoomAssignment(Room* r){
    rsrvRoom=r;
}

Room.h

#include "Reservation.h"
class Room {
public:
    static unsigned int roomNumber;
    unsigned int roomCapacity;
    Reservation* roomAvailability[30];
    double roomPrice;
    Room();
    ~Room();
    bool roomReservationAdd(Reservation*);
};

Room.cpp

#include <iostream>
#include <string>
#include "Room.h"

using namespace std;

/*
    Constructor & destructor
*/

bool Room::roomReservationAdd(Reservation* r){
    /* some statement that returns flase */
    r->rsrvRoomAssignment(/* & of created object */); // This is the problem i described.
    return 1;
}

I am pretty new to OOP so there might be some more logical errors on the above snipsets, so don't be harsh :) .

Thanks for any kind of help!

Upvotes: 0

Views: 126

Answers (1)

user1620443
user1620443

Reputation: 794

When inside a class method, this indicates the instance of the object calling it. In your case, when a room instance X calls X.roomReservationAdd(r), this points to the room instance X. Hence, you can simply call r->rsrvRoomAssignment(this);

Upvotes: 2

Related Questions