C++ Constructor, Inheritance, Access Modifiers and Stuff
// 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 wi开发者_开发百科th the protected one.
(i am using the .NET framework via visual-studio-2010, but i think this is more like a general c++ problem)
When I face this situation I added a member function for initializing common values, like for example an Init method called on both constructors.
use method
name this method init()
, for example.
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.
精彩评论