Archived

This topic is now archived and is closed to further replies.

perfectly_dark

Confusing Character

Recommended Posts

perfectly_dark    253
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

Share this post


Link to post
Share on other sites
JulianSpillane    122
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".

Share this post


Link to post
Share on other sites
jamessharpe    497
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.

Share this post


Link to post
Share on other sites
Miserable    606
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.

Share this post


Link to post
Share on other sites
Dobbs    164
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 itself

class 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;
};

Share this post


Link to post
Share on other sites