Home > other >  How to directly pass a string to a member function
How to directly pass a string to a member function

Time:12-29

I tried to create a class Person with data members: name and age; and member functions: getName and gerName. i was to create a parameter constructor in such a way that Person P1("Jeff",28) is a valid input.

#include <iostream>
using namespace std;
class Person
{
private:
    char* name;
    int age;
public:
    Person(char arr[],int n);
    ~Person();
    char *getName()const;
    int getAge()const;
};

Person::Person(char arr[],int n)
:name(arr),age(n)
{
}

Person::~Person()
{
}

char * Person::getName()const  //note that name and 
//the return type of this function both are pointers
{
    return name;
}

int Person::getAge()const
{
    return age;
}

then i did the application:

Person P1("Jeff",29);
    cout<<"name: "<<P1.getName()<<" age: "<<P1.getAge()<<endl;

the code was executed but i received an error: ISO C forbids converting a string constant to 'char*' [-Wwrite-strings]

on searching, i found out this error is received on executing faulty codes.

Is there a proper way to create a parameter constructor that satisfy my requirements? ( initialise an object as P1("Sam",22))

i expected the code to run smoothly, but i got an error which i don't know how to fix. I'm a beginner in coding and an example code or link to any resources will be appreciated.

CodePudding user response:

The problems are mainly:

  1. You do not use std::string
  2. In your constructor "char arr[]" will decay to char *arr
  3. The data type of the literal "Jeff" is const char[5]
  4. You cannot assign a const char[5] to a char *

Do not use a string literal in the call of the constructor.

First create a string, like char name[] = "Jeff" and then give name to the constructor.

Im my very humble opinion this should not even compile. My ISO c compliant compiler does not compile it. The resulting program will most likely show undefined behavior.

Use std::string in the first place. It is that easy and superior to char[] that it definitely should be used

  • Related