Reputation: 752
I need someone to show me what is wrong with this code. I don't know what's wrong with it. I know the code doesn't do anything meaningful and it can't be used. I created it only to know how copy constructors work.
class test
{
public:
int* value;
public:
int getvalue()
{return *value;};
test(int x){ value = new int(x);};
test(const test& a)
{
value=new int;
*value = a.getvalue();
};
};
Upvotes: 0
Views: 117
Reputation: 20335
(Posted on behalf of the OP).
I tried making the getvalue() function const and it worked. The problem was that I passed the test class as a const reference and because I didn't declare the getvalue() function const the compiler thought the function was going to change something in that reference.
Upvotes: 0
Reputation: 709
You need to change the declaration of getvalue()
to int getvalue() const
, since you're trying to call getvalue()
on a const reference in your copy constructor.
Upvotes: 2
Reputation: 309018
It's been a long time since I last wrote C++, but here goes:
I'm not sure why you're declaring value to be an int pointer; did you mean to make it an int?
class test
{
private:
int value;
public:
test(int x)
{
value = new int(x);
}
int getValue()
{
return value;
}
test(const test & a)
{
value = a.getValue();
}
};
Upvotes: 0
Reputation: 6834
There is a stray ; after each method definition, so will not compile.
class test { public:
int* value;
public:
int getvalue()
{return *value;}
test(int x){ value= new int(x);}
test(const test& a)
{
value=new int;
*value = a.getvalue();
}
};
Also, I'd avoid 'test' as a class name; depending on your platform if might be a macro or some other in-scpe name. Use "MyTest" or somesuch.
Upvotes: 1