Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why I cannot use "const string* sp = 0" to initialize in a constructor

Tags:

c++

g++

my problem is that const string* p gives me an error. What is wrong with this? since I am not change the original value. const int& n = 0 works fine.

#include <iostream>
using namespace std;
class HasPtr
{
private:
    int num;
    string* sp;
public:
    //constructor
    HasPtr(const int& n = 0, const string* p = 0): num(n), sp(p) {}
    //copy-constructor
    HasPtr(const HasPtr& m): num(m.num), sp(m.sp) {}
    //assignment operator
    HasPtr& operator=(const HasPtr& m)
    {
        num = m.num;
        sp = m.sp;
        return *this;   
    }
    //destructor
    ~HasPtr() {}
};
int main ()
{
    return 0;
}

output Error is :

error: invalid conversion from ‘const std::string*’ to ‘std::string*’
like image 826
ihm Avatar asked Oct 28 '25 08:10

ihm


2 Answers

private:
    int num;
    string* sp;

sp is non-const, but p is:

const string* p = 0

The result is that this sp(p) is basically this:

string* sp = (const string*)0;

It's complaining because doing this would remove the string's const-ness.

like image 116
Brendan Long Avatar answered Oct 29 '25 22:10

Brendan Long


This is because your sp member is not const.

string* sp;

But your parameter p is a const. The result is that you are trying to assign a const pointer to a non-const pointer - hence the error.

To fix this, you need to declare sp const at as well.

const string* sp;
like image 29
Mysticial Avatar answered Oct 29 '25 22:10

Mysticial



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!