Static classes like C#

  • Thread starter Thread starter Brian Richards
  • Start date Start date
B

Brian Richards

Is there a way to implement static classes in C++ the same way you do in C#?

static class CompanyInfo
{
public static string GetCompanyName() { return "CompanyName"; }
public static string GetCompanyAddress() { return "CompanyAddress"; }
//...
}
 
Brian Richards said:
Is there a way to implement static classes in C++ the same way you do in
C#?

Sure. Just leave off the "static" keyword" on the class definition :)

Seriously though - there's no C++ equivalent to a class that CAN'T have
instance methods - but you can just make a class and only create static
methods in it. For completeness, declare an unimplemented, private default
constructor so the class cannot be instantiated.

-cd
 
Carl said:
Sure. Just leave off the "static" keyword" on the class definition :)

Seriously though - there's no C++ equivalent to a class that CAN'T
have instance methods

free functions in a namespace?

Jeff Flinn
 
Free functions is how I had it before but I wanted to share the methods with
a C# assembly so I was refactoring to a class.

Thanks
 
Brian Richards said:
Is there a way to implement static classes in C++ the same way you do in C#?

static class CompanyInfo
{
public static string GetCompanyName() { return "CompanyName"; }
public static string GetCompanyAddress() { return "CompanyAddress"; }
//...
}

If you're using C++/CLI, declare a class to be both abstract and sealed:

#using <System.dll>

public ref class CompanyInfo abstract sealed
{
private:
CompanyInfo();

public:
static String^ GetCompanyName() {...}
static String^ GetCompanyAddress() {...}
...
}

Sean
 
Back
Top