What .NET Developers Must Know about C++ Classes: Listing 5

Delegating constructors in C++, C# and Java.

#include <string>
#include <stdlib.h>

class MyBase {
public:
  MyBase(const int field) : field_(field) {};
  // The following overloading gets a string and delegates construction
  // to the version that gets int.
  MyBase(const string fieldStr) : MyBase(atoi(fieldStr.c_str())) {}
  // in C#, the line above is:
  // MyBase(string fieldStr) : this(Int32.Parse(fieldStr)) {}
  // in Java,
  // MyBase(String fieldStr) { this(Integer.parseInt(fieldStr)); }
  
private:
  int field_;
};

class MyDerived : public MyBase {
public:
  MyDerived(const int field) :  MyBase(field) {...}
  // in C#, MyDerived(int field) :  base(field) {...}
  // in Java, MyDerived(int field) { super(field); ...}
}

About the Author

Diego Dagum is a software architect and developer with more than 20 years of experience. He can be reached at [email protected].

comments powered by Disqus

Featured

Subscribe on YouTube