Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:
C++
#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

Because 500 is not an address.
Doing this:
C++
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:
C++
int* ptr = new int;
...
*ptr = 500;
...
cout << "PTR = " << *ptr << endl << " VAL = " << val << endl << endl;
 
Share this answer
 
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.

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900