Confusing Character

Started by
4 comments, last by perfectly_dark 21 years, 1 month ago
I''m confused by one character I''ve seen in a few tutorials around the web. I''ve seen some classes declared with a '':'' in it. Here''s an example from the scripting tutorial: Instruction(opcode code) : _code(code) what does this do? At least what is it called so I can research it on the web, had no luck finding anything on it, a name would help. Thanks alot
Advertisement
I''m not too sure about that implementation, but I know you can use the colon to create what is called a bitfield.

A bitfield lets you define a variable of a specific number of bits for a data type.

For example:

int iByte : 2

Defines an integer type that has two bits to it only.
I''m not really an authority on them at all, so I''d recommend doing a Google search regarding "bitfields".
The colon is used in constructors. What is enables you to do is pass constructor arguments to the class variables, before they are created. This is called the preamble. It is useful because this way it can avoid copy construction as some objects can end up being created twice because it is created and then assigned a value rather than being created with the value.
What jamessharpe said. Additionally, it is necessary when a class contains constant fields that must be initialised, or when a member lacks a default constructor.
I know a little about bitfields, but I don''t think that''s a bit field because it''s a class constructor. Can a constructor be a bit field?
It signals the start of an initializer list (what jamessharpe called the "preamble" - I''ve never heard that name used for it). It is an optional section in a constructor that serves two purposes: calling a specific base class constructor and setting the initial value of member variables.


  // Here it''s simply used to initialize the value of an int// Not terribly useful, you can do the same basic thing within// the body of the constructor itselfclass Baz{public:  Baz() : mb(0) {}  Baz(int b) : mb(b) {}private:  int mb;};// What happens if you have Baz as a member variable and want// to initialize it with a non-default constructor?// Normally you would have to assign it in the body of the// constructor which entails creating a temporary object and// then doing a member-wise copy, instead you can do it like// this to avoid the intermediate value:class Foo{public:  Foo() {}  Foo(int f) : mbaz(f) {}private:  Baz mbaz;};// And similarly what if when you''re constructing an object// you want to call a specific superclass constructor for// the same reason? Just do it as follows:class Bar : public Foo{public:  Bar(int a, int b) : Foo(a), ma(b) {}private:  int ma;};  

This topic is closed to new replies.

Advertisement