0
votes

hey guys please have a look at this code.

class person
{
 char name[20];
 float age;

 public:
 person(char *s,float a)
  {
   strcpy(name,s);
   age=a;
  }
};

int main()
{
person P1("John",37.50);
person p2("Ahmed",29.0);
}

So in this class,the parametrized constructor takes a character pointer as an argument,and then passes the same to the strcpy function which copies the string to the character array name. If there is an integer array,like int arr[10]; then arr is a pointer to the first element. If there is a character array that is a string,like char str[]="Hello"; then str is a pointer to the first element,h in this case.So shouldn't we be passing something like str to the constructor?Why are we passing the character array elements,like "john","ahmed" to the constructor. Shouldn't we be doing - char str[]="ahmed"; person p1=(str,23);

3
arrays decay to pointers, so those are the same - Viktoria Andersson
This is invalid C++11. String literals are no longer allowed to be converted to char*. s should be a const char * if C strings are required. - chris
Since this is supposed to be C++ then why are you not using C++ std::strings ? Old skool C strings (char *) are a world of pain. - Paul R
In char str[] = "Hello";, str is an array; one which contains a copy of the elements of "Hello". It is not a pointer, particularly not to the first element of "Hello". It doesn't matter whether you're passing an array in the form of a string literal or as any other array, they both decay to a pointer to the first element. - molbdnilo

3 Answers

2
votes

Passing a string literal like "John" or "Ahmed" to a function/method means you are passing a pointer to its first character.

0
votes

from the compiler's point of view,

char str[];
char *str;

are both interpreted as pointers to char.

Given the function prototype person(char *s,float a) and the function call person("John",37.50) (in your case it's a constructor being called but the same applies), what the compiler actually generates is something like:

char *s = "John";
float a = 37.50;
person(s,a);

to be more exact, the sample code above and the function call person("John",37.50) should generate the same instructions.

0
votes

There is no real reason to use raw strings in this case. Since you are declaring a class, you obviously also do not need compatibility to the C programming language. So, just use ::std::string and your code will be more readable and in some situations even faster due to move semantics (used automatically be the ::std::string type).

#include <string>

class person
{
  ::std::string name;
  float age;

public:
  person(::std::string name, float age)
  : name(name)
  , age(age)
  {
  }
};