Expected Primary Expression error- member function woes

I get the error expected primary-expression before 'char' and I have no idea how to fix it. Any help is greatly appreciated. I have tried k.getname(char*), k.getname() etc...

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
#include <iostream>
#include <cstdlib>

using namespace std;

class Person
{
    private:
    char name[];

    public:
    Person();
    Person(char[]);
    void getname(char[]);

};
void Person::getname(char[])
{
    cout << "Please enter your name: ";
    cin >> name;

}
int main()
{
   Person k;
   k.getname(char); <-- This is where the error occurs
}
In your function void Person::getname(char[]){...} has incorrect syntax. There is no such thing as char[], but instead char Name[], or char* name. both do the same thing. Because you have not included a variable label in the function definition, the function is not complete. The constructor shares the same problem.

also, the private member name[] has been defined as a single member array. if you want to have more then one member to this array, consider using non-dynamic initialization:

1
2
3
//...
char name[256];
//... 


this declares a char array of 256 bytes.

consider using std::string. This standard library encapsulates all the hassle of using c-style strings, which is what you are doing when you use a char array. There's nothing with using c-style strings necessarily, but if you want to do something like this where ultimately the goal is to become familiar with classes and such, use std::string.

Last edited on
Thank you for your reply, I should know that stuff! Unfortunately, the assignment calls for using a char array. I have made the adjustments to the definition, declaration, and call but I am still getting the same error :(

edit: it seems to be a problem with how I am linking the class to main. if I remove the 'k' from 'k.getname(char name)' the program executes but the function is not called and nothing shows up.
Last edited on
That's because you are trying to pass a type to the getname function. You need to pass the actual object you want to manipulate to the function. However, since it's a member function you don't need to pass the array to the function at all since the char array will be within the member functions scope. So you can simply call the function as k.getname().

Actually, that call DOES pass an argument to the function. Member functions usually pass a pointer to the object for which they are called, to a parameter named this. But this is done implicitly by the compiler so you don't need to write it out in the function declarations/definitions. In the function definition you could type line 20 as cin >> this->name, but again, without qualifying the data member to be of a different object of the same type, the compiler implicitly converts name to be this->name.
Last edited on
Topic archived. No new replies allowed.