user3659335
user3659335

Reputation: 1

How to pass char as function argument in class?

#include <iostream>

using namespace std;

class X{
    private:
        char ime[50];
    X(char *c){ // or char (char c[]) which one to use?
        // how to set the value of c inside the ime[50];
    }
};

int main()
{

    return 0;
}

I want to pass a char as a function argument inside the constructor of a Class, so I can use two ways.. which one do I use? And once the value is passed, how do I put the value of c inside the char ime[50] variable of the class?

Upvotes: 0

Views: 3102

Answers (3)

AmitB
AmitB

Reputation: 752

There are a few things that you have to take into consideration:

  1. As others (merlin2011, juanchopanza) suggested above, if the argument is a null-terminated string, you are better off using std::string, and then using a copy routine such as std::copy to fill the data member array.

  2. You should pass the argument as const, as it is not being modified within the constructor's body (that is).

  3. If you are passing an array of char values (rather than a null-terminated string), you should pass the array's size as another argument to the constructor. Then, inside the constructor's body, use a copy routine (such as std::copy) to copy the the required amount of char values (as specified by the additional argument) to the data member array.

  4. In this case, there is no difference between the char* or char[] notation, as they will both specify a char pointer parameter that is being passed to a function. For more info about the difference between these notations, see this thread.

Upvotes: 0

merlin2011
merlin2011

Reputation: 75575

As the comment suggested, the easiest way to use std::string. Also, if your constructor is not public nobody can call it.

class X{
    private:
        std::string ime;
    public:
        X(const std::string& str) : ime(str) {
        }
};

If you insist on using char* though, and you are sure that you will only ever pass in a character array of length 50, you can use memcpy.

class X{
    private:
        char ime[50];
    public:
        X(const char* c) {
            memcpy(ime,c,50);
        }
};

If you insist on char* and you do not know how long the length is (only that it is less than 50), you will have to pass in the length.

class X{
    private:
        char ime[50];
    public:
        X(const char* c, int length) {
            if (length > 50) length = 50;
            memcpy(ime,c,length);
        }
};

Note that we use memcpy instead of strncpy because I am making no assumptions about what is inside your char[].

Upvotes: 2

NirMH
NirMH

Reputation: 4929

Both are the same, use C string copy routines to copy the data into the internal buffer.

pay close attention to the length of the string passed in, and copy only the first 50 characters.

But indeed, using std (string or vector, basic_str) is much more simple/safe to use

Upvotes: 0

Related Questions