1
// Inheritance.cpp : main project file.
#include "stdafx.h"

using namespace System;

ref class Base {
private:
    int value;
    int value2;
    Base() { this->value2 = 4; }
protected:
    Base(int n) {
        Base(); // <- here is my problem
        value = n;
    }
    int get(){ return value; }
    int get2(){ return value2; }
};

ref class Derived : Base {
public:
    Derived(int n) : Base(n) { }
    void println(){
        Console::WriteLine(Convert::ToInt32(get()));
        Console::WriteLine(Convert::ToInt32(get2()));
    }
};

int main(array<System::String ^> ^args) {
    Derived ^obj = gcnew Derived(5);
    obj->println();
    Console::ReadLine();
}

Console Output is:

0
5

i know, that i do call the Base() constructor, and i know that i create something like a new object, that vanishes after Base(int n) was called...

but i have no idea how i could combine my private default constructor with the protected one.

(i am using the .NET framework via visual-studio-2010, but i think this is more like a general c++ problem)

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Baarn
  • 673
  • 11
  • 23
  • 1
    In C++ you can not call a constructor from a constructor: http://stackoverflow.com/questions/308276/c-call-constructor-from-constructor – wkl Feb 24 '11 at 17:53
  • 1
    @birryee: sure you can -- but doing so constructs *another* object rather than delegating construction of the current object to the other constructor. – Jerry Coffin Feb 24 '11 at 18:32
  • yupp, exactly that was my problem :/ – Baarn Feb 25 '11 at 12:56

3 Answers3

2

When I face this situation I added a member function for initializing common values, like for example an Init method called on both constructors.

bcsanches
  • 2,362
  • 21
  • 32
  • ah ok, seems to be the best way then (especially when looking at the first comment below my question) – Baarn Feb 24 '11 at 18:06
2

use method
name this method init(), for example.

rmflow
  • 4,445
  • 4
  • 27
  • 41
0

The Base() constructor leaves value uninitialized and I'm not even sure that constructor is needed at all since it's private.

Just make sure that you adequately define your public API and only create constructors that are needed. Then in each constructor use the initializer list to assign all the attributes, to avoid working with uninitalized memory (typically try to avoid assigning in the body or a separate method to avoid possible double initialization.

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • the purpose of Base() was to set value2, it is private because its only purpose was to be only called by other constructors from the same class, like Base(int n) in this case, which sadly seems to be not possible – Baarn Feb 24 '11 at 18:10