Click here to Skip to main content
14,579,188 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hey! Can anyone tell me why my code is not giving me value of pointer ptr that is 500 in this code.Let me show you my code:
#include <iostream>
using namespace std;

class MyClass {

public:
    int* ptr = new int;
    int val;

    MyClass(int ptr=0,int val=0) :ptr(&ptr), val(val)
    {
        cout << "Default Constructor is called (Constructor Initializer List)" << endl << endl;
        ptr = 500;
        val = 80;
    }

    void show_constructor_initializer_value() {
        cout << "PTR = " << ptr << endl << "VAL = " << val << endl << endl;
    }

    ~MyClass() {
        cout << "Destructor called" << endl << endl;
        delete ptr;
    }
};


int main()
{
    MyClass m1;

    m1.show_constructor_initializer_value();
}


What I have tried:

I have tried all the methods that I know.
Posted
Updated 29-Jun-20 21:20pm
v2

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Because 500 is not an address.
Doing this:
int* ptr = new int;
...
ptr = 500;
Doesn't set the integer value, it sets the pointer to the integer value - i.e. it throws away the address of the integer, and replaces it with the value 500.

And that useless to you, because it's not an address. So when you try to print it later it tries to print the address and basically throws up it's hands in horror.

Probably what you meant to do was this:
int* ptr = new int;
...
*ptr = 500;
...
cout << "PTR = " << *ptr << endl << " VAL = " << val << endl << endl;
   
Comments
Member 14876295 29-Jun-20 12:34pm
   
Dude! I know this But I actually want this result in that type of syntax.can it be possible? If possible then kindly make a code for that line.
Member 14876295 29-Jun-20 12:36pm
   
In Short ! I wanna ask like can we initialize pointer in constructor initializor.
Member 14876295 29-Jun-20 12:36pm
   
In Short ! I wanna ask like can we initialize pointer in constructor initializor.
OriginalGriff 29-Jun-20 12:43pm
   
Not to a constant value, no - you have no idea where your memory is, so you can't use a constant as a memory address.
Member 14876295 29-Jun-20 12:56pm
   
Thanks! I got your point.
OriginalGriff 29-Jun-20 13:18pm
   
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100