Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include<iostream>
using namespace std;

class A
{
        public:
                int a;
        A(int a) : a(a) {       }
};

int main()
{
        A a(8);
        A b = a;
        printf("a=%p\n", &a);
        printf("b=%p\n", &b);
        cout<<a.a<<endl;

        A *c = new int();
}


Hi,
how to create an argument based constructor initialization with dynamic allocation.??

What I have tried:

tried to initilize but getting compilation error
Posted

For this one I think I can guess what the problem is but you should always include the compiler error messages you get because that makes it much easier for us to help.

Anyway, the problem is your member variable and the argument have the same name. I prefer to prepend all member variables with the "m_" wart so here is what that would look like :
C++
class A
{
public:
   int m_a;

   A( int arg ) : m_a( arg )
   {
   }
};
 
Share this answer
 
Comments
Richard MacCutchan 10-Oct-23 15:25pm    
The compiler is clever enough to distinguish between the parameter and the member variable.
Rick York 10-Oct-23 17:19pm    
Yes, you are right. It didn't used to be this way so I learned a long time ago not to do it. Regardless, you found the problem so have an up-vote from me.
Richard MacCutchan 11-Oct-23 3:41am    
Thanks. And, for the record, I also used to do it this way, based on my experiences in the early days of MFC.
When creating a dynamic object, you can pass the initialization arguments to the new operator, similar to creating an object on the stack
C++
A *c = new A(17);  // allocates space for a new A object with initializer "17"

cout << c->a << endl;  // prints 17

delete c;  //  returns allocated space to the heap


But these days, you should use smart pointers, instead of new/delete: Smart Pointers in C++ - GeeksforGeeks[^]
 
Share this answer
 
v2
Comments
CPallini 11-Oct-23 2:04am    
5.
The problem is at this line:
C++
A *c = new int();

The left hand side is OK, you declare c as a pointer to an A object. But the right hand side creates a pointer to an integer. But c is a pointer to an object of A, not an integer. So change it to:
C++
A *c = new A(0); // c now points to a new A object, initialised with a zero value; but it could be any integer value.
 
Share this answer
 
Comments
CPallini 11-Oct-23 2:03am    
5.
Richard MacCutchan 11-Oct-23 3:44am    
Thanks, Carlo.

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