The Secret Life of C++: Day 2: Basic Objects
We talked about structs in C. Lets take a look at C++ structs and classes.
Just Fields
First, a basic struct with no constructor:
basic-struct.cc,
basic-struct.s,
basic-struct.listing.
Some of the symbols we see here bear explaining:
- _Znwj
- Translates into the new operator over the type
unsigned int
- _ZdlPv
- delete a pointer to a void.
Simple Methods
Next, a basic class this time (really no difference), still no
constructor, this time we call some simple get/set methods:
basic-method.cc,
basic-method.s,
basic-method.listing.
Some symbols again:
- _ZN8onefield8setFieldEi
- method onefield::setField(int)
- _ZNK8onefield8getFieldEv
- Konst method onefield::getField(void)
Notice that the this
pointer gets passed as the first
argument to both functions, as you might expect.
Constructors
Lets give our simple object a constructor and a destructor, and
see how that goes:
basic-constructor.cc,
basic-constructor.s,
basic-constructor.listing.
And we get more symbols to decode:
- _ZN8onefieldC1Ei
- onefield Constructor (C1 means it a
is complete object constructor) that takes an int parameter.
- _ZN8onefieldD1Ev
- onefield complete object desctructor, no parameters.
Temporary Objects
When you call a function with an object, and you don't pass a
pointer/reference, the function gets a copy of the object.
Similarly when you return an object, there is a temporary one
created for the return.
Temporary Objects as Arguments
When passing a temporary object as an argument, the caller must
make space on the stack, call the constructor, pass a
reference/pointer to the object, and then call the destructor when
the life of the object is over. It could also be allocated on the
heap.
Lets look at the first case, using our onefield object again:
object-arg.cc,
object-arg.s,
object-arg.listing.
And some more symbols:
- _ZN8onefieldC1ERKS_
- onefield constructor that takes a
Reference to a Konst onefield.
S_
is
shorthand. In this case for onefield.
- _Z5print8onefield_Z5print8onefield
- This is our
print(onefield) function.
Temporary Objects as Return Values
When returning an object from a function, if the object is
non-trivial, than the caller allocates temporary space and passes
a pointer to the space as a first argument to the function. The
function calls the constructor. The caller is responsible for
calling the destructor when the object is no longer needed.
Examples, using a twofield object:
object-ret.cc,
object-ret.s,
object-ret.listing.
Richard Tibbetts
Last modified: Wed Jan 21 17:34:33 EST 2004