this pointer problem

V

Verbal Kint

hi everyone.

i am having a problem with the this-pointer in the code below. for the
command: "MyFunctB(this)"; i am getting the following error:
error C2664: 'cTest::MyFunctB' : cannot convert parameter 1 from 'cTest
*const ' to 'cTest'

whats the problem?
thanks.
V.K.

CODE:
class cTest
{
public:
cTest()
{
for (int i=0;i<3;i++)
dat = rand()%43;
}
void MyFunctA ()
{
MyFunctB(this);
}
void MyFunctB (cTest a)
{
}
private:
int dat[3];
};

int main()
{
int i=0;

srand(time(0));
cTest A;

A.MyFunctA();

_getch();
return 0;
}
 
D

Daniel T.

Verbal said:
i am having a problem with the this-pointer in the code below. for the
command: "MyFunctB(this)"; i am getting the following error:
error C2664: 'cTest::MyFunctB' : cannot convert parameter 1 from 'cTest
*const ' to 'cTest'

Your problem is exactly what the error says it is. The compiler cannot
convert a pointer to an object. (Namely, it can't convert a cTest*const
to a cTest.)
CODE:
class cTest
{
public:
cTest()
{
for (int i=0;i<3;i++)
dat = rand()%43;
}
void MyFunctA ()
{
MyFunctB(this);
}
void MyFunctB (cTest a)
{
}
private:
int dat[3];
};


Two possible fixes:

void cTest::MyFunctA() {
MyFunctB( *this );
}

Doing the above will give MyFunctB a copy of the object (i.e., inside
MyFunctB, *this == a, but this != &a.)

or

void cTest::MyFunctB( cTest* a ) {
}

Fixing it this way will mean that 'a' points to the exact same object
as this. (i.e.; inside MyFunctB, this == a.)

Which solution is best depends on what you are trying to accomplish.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top