Click here to Skip to main content
15,501,490 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi I have a problem
I have a base class :

C++
class Base
{
public:
    myClass* a;
    virtual void Update(){}

};

and another class :

C++
class NewClass:public Base
{
public:
    NewClass();
    virtual void Update()
    {
        a->val=200;
    }
}


now I do this :
C++
myClass* b;
Base me;
me=NewClass();
me.a=b;
me.Update();


but now b dont change. I want change b value. how can I do this like this ?
Posted
Updated 30-Dec-12 23:37pm
v5

I haven't tried it but I wouldn't expect your code to compile.

You are describing 3 classes here: Base, NewClass and myClass. Base includes a pointer to myClass, which in your code as provided, is not defined (error). If you somehow overlook this and define it somehow, in the lower section of code:

1    myClass* b;
2    Base me;
3    me=NewClass();
4    me.a=b;
5    me.Update();


Lines 2 and 3 could be combined as

2/3    Base me=NewClass();


which represents use of a copy constructor, building a new 'Base' object, copying elements from a new 'NewClass' temporary object. At this point, me.a is undefined (usually trash from the stack with most compilers). Line 4 should assign me.a the value of b (on the stack) and line 5 will change b->val.

Assumptions:
(1) We are talking C++ here. Java for example does something different.
(2) This code segment is external to the classes in question.
(3) myClass contains something named 'val' (which is well formed POD and not a property or something else funky).

You didn't provide the code for class myClass, which could change all of the above.
 
Share this answer
 
I am sorry, but you have confused the usage of pointers

C++
a=200; // is wrong


you probably want to do

C++
*a = 200;
 
Share this answer
 
v3
Comments
mohammadali1375 31-Dec-12 4:37am    
Oh I'm sorry. I try make an example from my problem quickly . Now I edit my question;
Mattias Högström 31-Dec-12 10:25am     CRLF
The code didn't become clearer. Theoretically, the assignment looks ok now, but your code contains a couple of errors and omissions. I don't think it compiles, so I am not sure what the error is. 1. Allocate myClass object or use an object. myClass* b = new myClass(); myClass b; 2. When using subclasses and virtual methods, a pointer must be used. Base me; me=NewClass(); === Change to ===> Base *me = newClass(); 3. Exposing a public variable is bad practise, and of pointer type, is worse. If you really need to pass around pointers, use the constructor and/or get set methods. The reference type (myClass& par) is even better than pointers because it can't be null. A "smart pointer" is even better to use than raw pointers. http://en.wikipedia.org/wiki/Smart_pointer

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