6

I've been away from C++ for a while, and I'm having a little trouble with this one. I'll spare you my bad code - can someone please post a 'model answer' for how to write a simple header file and source file for a small class with a constructor that accepts a few values, and passes a few on to it's base classes constructor? I'm worried that I'm making something inline by mistake. Thank you.

Sometimes the simplest answers are the hardest to find clear examples of on the internet.

1
  • What are you worried about with regards to inlining? Commented Oct 7, 2011 at 17:22

4 Answers 4

9
// ExampleClass.h
#ifndef ExampleClass_H_
#define ExampleClass_H_

#include "ExampleBase.h"

class ExampleClass : public ExampleBase {
public:
    ExampleClass(int a);
};

#endif


// ExampleClass.cpp
#include "ExampleClass.h"

ExampleClass::ExampleClass(int a) : ExampleBase(a)
{
    // other constructor stuff here
}
Sign up to request clarification or add additional context in comments.

Comments

6

The initializer list is used to initialize the base classes. Initialize base classes before instance members. Non-virtual base classes are initialized from left to right, so if you have multiple bases, initialize them in the order they are declared.

Here's an example of passing arguments to the base class constructor:

#include <iostream>

struct Base {
    Base(int i) {
        std::cout << i << std::endl;
    }
};

struct Derived : public Base {
    Derived(int i) : Base(i) {}
};

1 Comment

Honestly, I'm a little surprised that I can't find a simple example like this in the C++ FAQ. If anyone can drop a link to the appropriate section, I'd appreciate it.
4

Seeing as the OP requested non-inline versions, I'll repost with modifications.

struct Base {
    Base (int);
};

struct Derived : public Base {
    Derived (int);
};

Derived :: Derived (int i)
: Base (i)
{
}

Comments

2
class Parent
{
    // Parent Constructor
    Parent(int x)
    {
        // Constructor Code
    }
};

class Child : public Parent
{
    // Child Constructor  
    Child(int x, int y, int z) : Parent(x)
    {
        // Constructor Code
    }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.