Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pass an object into another object?

Tags:

c++

class

logic

I don't know if I've missed something, but I can't seem to figure out how to make this work, and couldn't find the answer online.

Lets say I have a two classes, Class A, and Class B. (stored in separate files)

Class A has a function setName() that sets a variable within a Class A object.

Class B has a function setOtherName() that sets the value of a Class A object's name.

So I set setOtherName() up like so:

void setOtherName(ClassA& cla)
{
*cla.setName("foobar");
}

then my main script looks like so:

Class A burger;
Class B fries;
fries.setOtherName(*burger);

this does not work in my orignal script, I get the following error:

error: no matching function for call to 'ClassB::setOtherName(ClassA*&)

Any help is aprreciated! ( sorry for any confusion )

Actual code: main.cpp:

#include <iostream>
#include "quests.h"
#include "player.h"
#include <string>
#include <cstdlib>

using namespace std;

int main()
{
    quests GameQuests;
    player Player;
    GameQuests.quest1(Player);
    Player.main();

    return 0;
}

quests.cpp:

#include "quests.h"
#include "player.h"
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

void quests::quest1(player& charact){
    cout << "By the way, what was your name?" << endl;
    person1=4;
    system("pause");
    charact->setName();
}
like image 667
Sam Tubb Avatar asked Jun 29 '15 00:06

Sam Tubb


1 Answers

The implementation of your setOtherName function should have the signature

void ClassB::setOtherName(ClassA& cla)

You need to specify that it is included in ClassB. Within your class definition of ClassB, make sure to include

void setOtherName(ClassA&);

Furthermore, since your variable burger is of type ClassA and not of type ClassA*, there is no need to dereference the variable upon passing it into the function. Call it like

fries.setOtherName(burger);

You have also incorrectly dereferenced the variable cla. That object is passed by reference, not pointer, so there is no need to dereference.

like image 111
Daniel Avatar answered Sep 18 '22 20:09

Daniel