C++ Parent Class and Member Initialization

This is a small bit of code to remind me of what I learned today about how to pass values to a parent class, as well as initialize member variables in the child class constructor.

class ParentClass
	ParentClass(int x)
		printf("ParentClass was passed: %i\n", x);

class ChildClass : ParentClass
	int y;
	ChildClass(int x)
		: ParentClass(x), y(x)
		printf("In ChildClass, y is: %i\n", x);

int main(int argc, char* argv[])
	ChildClass childclass(42);
	return 0;

The output is:
ParentClass was passed: 42
In ChildClass, y is: 42

It’s not obvious to me how to split out the implementation from the interface in this case, however. Err… is “interface” and “implementation” the correct C++ lingo? That’s what it’s called in Objective-C. Hmm.

This entry was posted in Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s