signature of public member contains native type - windows-runtime

I am new to visual c++, I have the following code:
ref class Book sealed
{
public:
Book(std::string title,std::string author,int year);
void setTitle(std::string title);
std::string getTitle() const;
int getYear() const;
void setYear(int year);
void setAuthor(std::string author_);
std::string getAuthor() const;
private:
std::string title_;
std::string author_;
int year_;
};
When I am trying to compile it I am getting the following error:
{ctor} signature of public member contains native type. I suppose this is because I am using an the std::string and not the Platform::String, how can I fix that?

Your ref class is not marked public itself, so it appears you are only consuming this class internally (as source) from other C++, and not intending for it to be published to other WinRT consumers.
If this is the case, you can set your constructor as internal instead of public, which will be public within this component and not visible externally. And really if that's your intended usage, then it can just be a regular 'class' instead of a 'ref class'. If you do wish to use it across the WinRT boundary but you don't need the constructor, you can make it a 'public ref class' and have the constructor marked as 'internal'. Kinda depends on your scenario.
If you instead wish to make this class public and have a public constructor which is usable across the WinRT boundary (so that it can be consumed by C#/VB/JS), then you need to use WinRT types (such as Platform::String). Within your class the storage type can still be a std::string (although I recommend using std::wstring, otherwise you need to do wide-to-narrow conversions, as Platform::Strings are wide strings).
To convert between these two types, use Platform::String::Data() to get at the underlying wchar_t* which you can use to construct a std::wstring. And similarly, Platform::String has a constructor which takes a wchar_t* (which you can get from std::wstring::c_str()).

You can't hold native types in a managed reference class.
You can only hold a pointer to an unmanaged object(a pointer is just a number after all, and that's why it's allowed).

Related

Public ref class implementing internal interface in C++/CX

I have a Windows Runtime component in which all of my classes need to expose a handle internally:
private interface class IHandleContainer {
IntPtr GetHandle();
}
namespace Foo {
public ref class Bar: IHandleContainer { ... }
public ref class Baz: IHandleContainer {
internal:
virtual IntPtr GetHandle() = IHandleContainer::GetHandle;
}
}
I don't need IHandleContainer to be public, but I do need IHandleContainer to be on the interface list so that each of my internal objects can be safe_cast<IHandleContainer> successfully.
Being outside of a namespace, IHandleContainer should not be emitted to metadata, but should have a COM GUID associated with it and by listing it on the ref class's interface list, CX should be able to wire up the correct response to QueryInterface. Structurally, everything should "just work." But the compiler isn't cooperating:
error C3991: 'Foo::Baz': cannot implement a non-public or nested interface 'IHandleContainer'
Unfortunately this is not possible using C++/CX, and none of the tricks you might try will work.
Interface members can't be internal
There is no such thing as internal inheritance
public WinRT types can't derive from private bases
WinRT types can't derive from non-WinRT types
public WinRT types can't be unsealed unless they derive from something that is unsealed
That last one is recursive, and the only way out of it is to derive from an existing unsealed platform-provided type like DependencyObject, but you really don't want to do that.
You need to use something CloakedIid in WRL, or Kenny Kerr's pure C++ example on MSDN Magazine. Either way you have to define your types in IDL and implement them the "hard" way.

How to declare static field in class

I have a XAML + DirectX app and I want to add static field to my "interop" class:
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Direct3DInterop sealed : public Windows::Phone::Input::Interop::IDrawingSurfaceManipulationHandler
{
public:
static int VALUE = 0;
...
};
It does not compile saying "only static const integral data members can be initialized within a class".
If I change it to const static int VALUE = 0; then it still does not compile with error "a non-value type cannot have any public data members"
What am I doing wrong?
WinRT public classes have a number of limitations to ensure they are consumable by multiple languages including C++, JavaScript, and C#. This is why you are getting error C3984. You can't have public fields and instead must use properties. You'd make it a read-only property:
property int VALUE
{
int get() { return 0; }
}
It is important to remember that properties are function calls and can't usually be optimized away, so you should consider that when designing the interfaces.
If you intend to have this class only consumable by C++, consider not using a WinRT class and instead use a simple C++ class which you managed the lifetime using std::unique_ptr or std::shared_ptr. In that case, you can of course use the public field approach as always.
The original problem you got is a general C++ language restriction not specific to WinRT. Error C2864 (you are using VS 2012 from the text you posted) is a little more general with C++11 in VS2013.

Should a class ever have static and non-static members

I'm trying to figure out when it would be appropriate for a class to have both static and non-static functions. AKA:
$obj = new ClassA;
$obj->doOOPStuff();
$something = ClassA::doStaticStuff();
Note: This example is done in PHP, however the question is language agnostic .
It seems that if you have a class that is meant to be instantiated, any functions that can be called statically, most likely belong in another class.
Is there any viable cases where I would have a class that used static AND non-static members?
One example: when Creation has to happen in a specific way.
class Foo {
public:
static Foo* Create(...params...);
private:
Foo();
};
Consider String class in .NET. It contains a non-static Split method which breaks some instance into a string[] and a static Join method, which takes a string[] and transform it into a string again.
A static method is applicable when you don't need to keep any state. So Math.Sin() just depends on its parameters and, given same parameters, output will always be the same. A non-static method can have different behavior is called multiple times, as it can keep a internal state.
If the functionality provided by static methods is relevant to that class and its objects, why not. It is pretty common.
Static method are most often factory methods
public class MyClass {
public static MyClass createMyClass(int a, double b) {..}
public static MyClass createSubclassOfMyClass(int c, boolean cond) {..}
public int calculateThis();
public double calculateThat();
}
Another use is to access some property that is logically bound that that class, but not separately to instances. For example - a cache:
(Note - of course synchronization should be taken into account in this example)
public class MyClass {
public static final Cache cache = new Cache();
public static void putInCacheIfNeeded(Object obj) {..}
public static void replaceInCache(Object obj) {..}
public void doSomethingCacheDependend(Object obj) {
if (something) {
MyClass.putInCacheIfNeeded(obj);
} else {
MyClass.replaceInCache(obj);
}
}
}
(Java language for the examples)
Imagine your constructor has two overloads that both are strings:
public class XmlDocument
{
public static XmlDocument CreateFromFile(string filePath);
public static XmlDocument CreateFromXml(string xml);
}
The static function can provide meaningful name to the constructor.
$dialog = DialogFoo::createOpenDialog();
$dialog = DialogFoo::createDocumentOpenDialog();
$dialog = DialogFoo::createImageOpenDialog();
It could also be used to enforce Singleton pattern.
$dialog = DialogFoo::getInstance()
Static class members are most useful where everything must either be in an object or be in a global scope; they are less useful in a language such as Python that supports module-level scopes.
I use static methods to instantiate new objects when I dont want the to give access to the constructor. I ensure that any necessary preconditions are carried out on the class before creating and object. In this example I have a counter to return how many objects are created, if I have 10 objects I prevent any more from being instantiated.
class foo {
private:
static int count;
foo() {}
public:
static foo bar() {
count++;
if (count<=10){
return new foo;
} else {
return null;
}
Let's assume a class has instance methods, here are some good use case for having static methods too:
For static utility methods
Such methods apply to any instance, for example String.format(String, Object...) in Java.
Use them when you don't want to create a specific instance for the job.
For static factory methods
Factory methods are methods that simply instantiate objects like the getInstance() and valueOf() methods in the Java API. getInstance() is the conventional instantiation method in singletons while valueOf() are often type-conversion methods, like in String.valueOf(int).
Use them to improve performance via object-caching, in interface-based frameworks (like the Collections Framework in Java) where you may want to return a subtype, to implement singletons (cough).
In general, static functions produce functionality highly related to class itself. It may be some helper functions, factory methods etc. In this case all functionality contains in one place, it correspond to DRY principle, increases cohesion and reduces coupling.

private/public class in namespace problem

This is a question about what defining a class as public or private does.
Right now, I have various classes defined inside of a namespace and I only want some of those classes to be visible/usable to the outside world.
So, for example, if the classes below were the only ones in the program, I would want main.cpp to only be able to see/use the MyPublic class, not the MyPrivate class. I thought that defining the MyPrivate class as private and the MyPublic class as public would accomplish this, but the below code works and main.cpp is able to declare a MyPrivate object.
Is it possible to do this in C++?
MyPrivate.h:
namespace MyNamespace{
// only classes inside of the MyNamespace should be able
// to use this
private ref class MyPrivate{
...
};
}
MyPublic.h:
#include "MyPrivate.h"
namespace MyNamespace {
// anyone can declare this
public ref class MyPublic{
...
private:
MyNamespace::MyPrivate^ p;
...
};
}
Main.cpp:
#include "MyPublic.h"
int main(){
MyNamespace::MyPublic p_yes; // this is fine
MyNamespace::MyPrivate p_no; // don't want this to be possible
return 0;
}
private/public in this situation will affect how classes are visible outside an assembly, if you want to create a class that is "private" in the meaning that it can be used only by some other class, you can use nested clas mechanism, like this:
namespace MyNamespace {
public ref class MyPublic {
private:
ref class MyPrivate {
public:
int x;
};
MyPrivate^ p;
};
}
//Edit:
You can by the way still throw this nested class in public: section and use it like this:
MyNamespace::MyPublic::MyPrivate priv;
The private keyword means something else than you think. I limits visibility of the ref class beyond the assembly. Since your Main() method is in the same assembly, it has no trouble referencing the type name. Note that the C# language's "internal" keyword means the same thing.
I assume that you really intend for these classes to be in a separate assembly someday. As such, using private is certainly good enough. Using nested private classes can make a class inaccessible to code in the same assembly.
You public header shouldn't include private header. Forward declare private class and include header only in MyPublic.cpp. Or that's what I'd say if you used normal C++. Bastardized .Net dialect might change things.
Unfortunately, the access modifiers on a class only affect visibility outside the assembly you're building. C++ doesn't support any sort of access modifiers that apply to namespaces in the way you're describing.
A common idiom for simulating this is to put the "private" code into a detail namespace (e.g. put it in MyNamespace::detail). This is used a lot in e.g. the boost libraries. By convention, code in a detail namespace should only be used by code in the enclosing namespace (so MyNamespace::detail should only be used by code in MyNamespace), although the compiler won't enforce this for you.

What Does "Overloaded"/"Overload"/"Overloading" Mean?

What does "Overloaded"/"Overload" mean in regards to programming?
It means that you are providing a function (method or operator) with the same name, but with a different signature.
For example:
void doSomething();
int doSomething(string x);
int doSomething(int a, int b, int c);
Basic Concept
Overloading, or "method overloading" is the name of the concept of having more than one methods with the same name but with different parameters.
For e.g. System.DateTime class in c# have more than one ToString method. The standard ToString uses the default culture of the system to convert the datetime to string:
new DateTime(2008, 11, 14).ToString(); // returns "14/11/2008" in America
while another overload of the same method allows the user to customize the format:
new DateTime(2008, 11, 14).ToString("dd MMM yyyy"); // returns "11 Nov 2008"
Sometimes parameter name may be the same but the parameter types may differ:
Convert.ToInt32(123m);
converts a decimal to int while
Convert.ToInt32("123");
converts a string to int.
Overload Resolution
For finding the best overload to call, compiler performs an operation named "overload resolution". For the first example, compiler can find the best method simply by matching the argument count. For the second example, compiler automatically calls the decimal version of replace method if you pass a decimal parameter and calls string version if you pass a string parameter. From the list of possible outputs, if compiler cannot find a suitable one to call, you will get a compiler error like "The best overload does not match the parameters...".
You can find lots of information on how different compilers perform overload resolution.
A function is overloaded when it has more than one signature. This means that you can call it with different argument types. For instance, you may have a function for printing a variable on screen, and you can define it for different argument types:
void print(int i);
void print(char i);
void print(UserDefinedType t);
In this case, the function print() would have three overloads.
It means having different versions of the same function which take different types of parameters. Such a function is "overloaded". For example, take the following function:
void Print(std::string str) {
std::cout << str << endl;
}
You can use this function to print a string to the screen. However, this function cannot be used when you want to print an integer, you can then make a second version of the function, like this:
void Print(int i) {
std::cout << i << endl;
}
Now the function is overloaded, and which version of the function will be called depends on the parameters you give it.
Others have answered what an overload is. When you are starting out it gets confused with override/overriding.
As opposed to overloading, overriding is defining a method with the same signature in the subclass (or child class), which overrides the parent classes implementation. Some language require explicit directive, such as virtual member function in C++ or override in Delphi and C#.
using System;
public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I'm just a generic drawing object.");
}
}
public class Line : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Line.");
}
}
An overloaded method is one with several options for the number and type of parameters. For instance:
foo(foo)
foo(foo, bar)
both would do relatively the same thing but one has a second parameter for more options
Also you can have the same method take different types
int Convert(int i)
int Convert(double i)
int Convert(float i)
Just like in common usage, it refers to something (in this case, a method name), doing more than one job.
Overloading is the poor man's version of multimethods from CLOS and other languages. It's the confusing one.
Overriding is the usual OO one. It goes with inheritance, we call it redefinition too (e.g. in https://stackoverflow.com/users/3827/eed3si9n's answer Line provides a specialized definition of Draw().