User forums > General (but related to Code::Blocks)

C++ n00b needs help

(1/2) > >>

R4ZOR:
Hello!

Please help me to understand c++ better:
If I have a class ClassA, and a class named ClassB, which is derived from ClassA.
If I have a function:

--- Code: (cpp) ---int f(ClassA x) {}
--- End code ---
can I pass a variable of type ClassB to this function?

--- Code: (cpp) ---ClassB b = new ClassB;
f(b);
--- End code ---
:(
Thnaks in advance:
R4ZOR

guest:
use references or pointers

R4ZOR:
How do you mean that?

David Perfors:

--- Code: ---int f(ClassA* x) {}

ClassB b = new ClassB();
f(&b);

--- End code ---
I think he is meaning this, I am not sure if this will work.. You have to try ;)
For me programming is always trying.. That's because one thing works for C++ but not for Java or C#...

gkuznets:
first of all not

--- Code: (cpp) ---ClassB b = new ClassB;
--- End code ---
but

--- Code: (cpp) ---ClassB* b = new ClassB;
--- End code ---

secondly of course you can write

--- Code: (cpp) ---f(ClassA x) {}
ClassB* b = new ClassB;
f(*b);

--- End code ---
and your compiler will interpret this in the following way:

--- Code: (cpp) ---f((ClassA)(*b)); // TYPECASTING!!!

--- End code ---
And inside f will be called member functions of CalssA even if they are overrided in ClassB.

thridly (MAIN SURPRISE)
all changes applyed to x inside f(ClassA x) will not have effect on b!
declaration f(ClassA x) means that inside f will be passed temporarry copy of object *b, which is to be destroyed after exiting from f.
Try to read some books on c++ and start from passing arguments to functions.
(Excuse my poor english)

Navigation

[0] Message Index

[#] Next page

Go to full version