Author Topic: C++ n00b needs help  (Read 4175 times)

R4ZOR

  • Guest
C++ n00b needs help
« 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: C++
  1. int f(ClassA x) {}
can I pass a variable of type ClassB to this function?
Code: C++
  1. ClassB b = new ClassB;
  2. f(b);
:(
Thnaks in advance:
R4ZOR

guest

  • Guest
Re: C++ n00b needs help
« Reply #1 on: April 30, 2006, 11:01:36 am »
use references or pointers

R4ZOR

  • Guest
Re: C++ n00b needs help
« Reply #2 on: April 30, 2006, 11:33:21 am »
How do you mean that?

Offline David Perfors

  • Developer
  • Lives here!
  • *****
  • Posts: 560
Re: C++ n00b needs help
« Reply #3 on: April 30, 2006, 11:40:43 am »
Code: [Select]
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#...
OS: winXP
Compiler: mingw
IDE: Code::Blocks SVN WX: 2.8.4 Wish list: faster code completion, easier debugging, refactoring

gkuznets

  • Guest
Re: C++ n00b needs help
« Reply #4 on: April 30, 2006, 12:21:39 pm »
first of all not
Code: C++
  1. ClassB b = new ClassB;
but
Code: C++
  1. ClassB* b = new ClassB;

secondly of course you can write
Code: C++
  1. f(ClassA x) {}
  2. ClassB* b = new ClassB;
  3. f(*b);
  4.  
and your compiler will interpret this in the following way:
Code: C++
  1. f((ClassA)(*b)); // TYPECASTING!!!
  2.  
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)

Offline thomas

  • Administrator
  • Lives here!
  • *****
  • Posts: 3979
Re: C++ n00b needs help
« Reply #5 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

"We should forget about small efficiencies, say about 97% of the time: Premature quotation is the root of public humiliation."

Offline enex

  • Single posting newcomer
  • *
  • Posts: 5
Re: C++ n00b needs help
« Reply #6 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