Code::Blocks Forums

User forums => General (but related to Code::Blocks) => Topic started by: R4ZOR on April 30, 2006, 07:31:00 AM

Title: C++ n00b needs help
Post by: R4ZOR on April 30, 2006, 07:31:00 AM
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) Select
int f(ClassA x) {}
can I pass a variable of type ClassB to this function?
Code (cpp) Select
ClassB b = new ClassB;
f(b);

:(
Thnaks in advance:
R4ZOR
Title: Re: C++ n00b needs help
Post by: guest on April 30, 2006, 11:01:36 AM
use references or pointers
Title: Re: C++ n00b needs help
Post by: R4ZOR on April 30, 2006, 11:33:21 AM
How do you mean that?
Title: Re: C++ n00b needs help
Post by: David Perfors on April 30, 2006, 11:40:43 AM
int f(ClassA* x) {}

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

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#...
Title: Re: C++ n00b needs help
Post by: gkuznets on April 30, 2006, 12:21:39 PM
first of all not
Code (cpp) Select
ClassB b = new ClassB;
but
Code (cpp) Select
ClassB* b = new ClassB;

secondly of course you can write
Code (cpp) Select

f(ClassA x) {}
ClassB* b = new ClassB;
f(*b);

and your compiler will interpret this in the following way:
Code (cpp) Select

f((ClassA)(*b)); // TYPECASTING!!!

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)
Title: Re: C++ n00b needs help
Post by: thomas on April 30, 2006, 12:25:19 PM
This is not a "how to learn C++" forum or FAQ, sorry. There are plenty of sites on the web that deal with such things.

You may for example want to read http://www.parashift.com/c++-faq-lite/basics-of-inheritance.html

Title: Re: C++ n00b needs help
Post by: enex on April 30, 2006, 06:29:35 PM
A Crash Course in C++
http://media.wiley.com/product_data/excerpt/41/07645748/0764574841.pdf

Pretty good if you are already familiar with other OO languages like Java.. etc