I have a class called MyClass

in main, I have

MyClass A; //calls the default constructor
A.date = 4;

I would like a function to do some stuff and then use one of A's constructors , the result being I have A back in main

class MyClass
{
public:
int name;
int date;
MyClass(){};
MyClass(int i)
{
name = i;
}

};

void MyFunc(MyClass &A)
{
 int i = 3;
MyClass A(3);
}

Can you do this at all? Back in main, will A have date=4 and name=3? or just date=4?

Thanks!

Dave

>>Can you do this at all
Sortof. What you do is write a public Initialize() method for class A so that it can be called by the class constructor as well as by anyone else.

class A
{
private:
    int x;
public:
    A() { Initialize(); }
    A(int w) {x = w;}
    Initialize() { x = 0; }
};

int main()
{
    A a(3);
    a.Initialize();
}

Or you can just reassign A with the new object.

class MyClass
{
public:
int name;
int date;
MyClass(){};
MyClass(int i)
{
name = i;
}

};

void MyFunc(MyClass &A)
{
// int i = 3;  //-- this isn't needed
A = MyClass(3);  // discard the old, and assign the new
}

so that totally undos everything that was done to / stored in A and sets A.name to 3 (and now date is a junk pointer)?

Thanks,
Dave

so that totally undos everything that was done to / stored in A and sets A.name to 3

yes.

Why do you even want to call the constructor? why not just A.name = newvalue instead, like you did for A.date.

(and now date is a junk pointer)?

As far as I can see, date was never a pointer

This article has been dead for over six months. Start a new discussion instead.