Can't figure out why the code crashes in C++

The compiler just crashes when I try to run the code and I can't find the problem.

I get this error: 0xC0000005: Access violation reading location 0x00000000. So it must be a pointer error.

But I can't seem to figure out what I did wrong. So if someone can help me it would be very appreciated.

classB.ccp

ClassB::ClassB(ClassC *CPtr, int x)
{
    ClassC *CPtr_ = CPtr;
    x_ = x;
}

void ClassB::print() const
{
    CPtr_->print();
    std::cout << x_ << std::endl;
}

ClassC.ccp

ClassC::ClassC(int y)
{
    y_ = y;
}

void ClassC::print() const
{
    std::cout << y_ << std::endl;
}

main

ClassC myCObject(7);
ClassB myBObject(&myCObject , 11);
myBObject.print();

Upvotes: 0

Views: 77

Answers (3)

AntiClimacus
AntiClimacus

Reputation: 1420

Here, CPtr_ is a local variable. I guess that you would like to store CPtr in an attribute of ClassB. Maybe there is one, and the local variable shadows it.

ClassB::ClassB(ClassC *CPtr, int x)
{
    ClassC *CPtr_ = CPtr;
    x_ = x;
}

Upvotes: 3

lcjury
lcjury

Reputation: 1258

ClassB::ClassB(ClassC *CPtr, int x)
{
    ClassC *CPtr_ = CPtr;
    x_ = x;
}

when you call your constructor you're creating a ClassC pointer, but when the constructor ends that pointer is destroyed becouse it's a local variable

add your

ClassC *CPtr_;

var to the definition of your class, then, the constructor must look something like

ClassB::ClassB(ClassC *CPtr, int x)
{
    CPtr_ = CPtr;
    x_ = x;
}

Upvotes: 1

AnT stands with Russia
AnT stands with Russia

Reputation: 320361

In the constructor of class ClassB you stored the parameter value CPtr in a local variable CPtr_. Why did you do that?

Apparently, the idea was to store in the data member CPtr_ of ClassB. Yet, for some unexplainable reason, you decided to declare a local variable with the same name in the constructor. Because of that extra variable, the data member remains uninitialized (contains garbage) and the code crashes when you attempt to dereference it.

Upvotes: 5

Related Questions