Reputation: 89
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);
Upvotes: 0
Views: 1125
Reputation: 34618
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)
{
}
};
Upvotes: 0
Reputation: 4951
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.
Upvotes: 0
Reputation: 105992
Passing a string literal like "John"
or "Ahmed"
to a function/method means you are passing a pointer to its first character.
Upvotes: 2