Using object as function parameter

Can someone please tell me whatsup?

I just want to be able to use objects as function parameters, can someone tell me what im doing wrong? In decent terms please, been trying to learn c++ for like 4 months and haven't really gotten anywhere cause I cant seem to find any decent answers that dont try to get me to completely forget and relearn every single thing I've done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;


class pData
{
public:
	string pName;
};


void input(string x);


int main()
{
    
	pData pObj;
	cout << pObj.pName << endl;
	input(pObj& pName);

}


void input(string x)
{
	string i;
	cin >> i;
}
A string is a kind of object. So this function:

void input(string x);

takes a string object as a parameter. So when you call it, you need to pass a string object.

Let's look at where you try to use it:

input(pObj& pName);

Well, you've got that totally wrong. That's not how to call a function. Let's look at some simple examples.

Here's a function that accepts an int:

void function(int the_input_parameter);

Here's how it would be called:
function(3);
or
1
2
int x = 7;
function(x);


See how we called it? We did NOT call it like this:

function (int 3);

We did NOT call it like this:

1
2
int x = 7;
function(int x);


When you are declaring or defining the function, you need to specify the type of the parameter. When you call it, you do NOT specify the type.

Back to your problem. Here's the function declaration:
void input(string x);
So how might we call that? Here's a way:
1
2
string y;
function (y);

See how when we call it, we DO NOT specify the type of the parameter.

So let's look at how you tried to call it:
input(pObj& pName);
So you tried to specify the type of the parameter when you called it. As we just went over, that's bad. You do NOT specifiy the type of the parameter when you call a function. It appears you tried to tell it that it was being passed a reference to a pObj object, which doesn't even exist. What a mess.


Basic function calling is really important. If you have trouble calling functions, you need to stop and go back.

I suspect you wanted to pass the function the string inside the object named pObj?

input(pObj.pName);
Note that nowhere in that call do we specify the type of the object. We just pass the string.

Last edited on
Thank you my dude, youre perfect. Havent messed around with c++ in a month or so my bad on that function call, but again youre perfect.
Topic archived. No new replies allowed.