Calling Method/Function outside a Class but on the same namespace in c++/cli - visual-c++

I have a very simple and yet complicated (atleast for me) question on how to call a method/function outside a class but on a same namespace in c++/cli.
I know that you need to create an instance of an object before you can call a method which is inside a class, something like:
namespace Cars {
public ref class MyClass
{
void Honda(int i)
{
//some code
}
}
void Register()
{
MyClass c;
c.Honda(1);
//some code
}
}
But how do I do the opposite? Like how do I call Register() inside the MyClass::Honda function if they are on the same namespace but not on the same class?
I tried Cars::Register() but it gives an error saying that:
Register() is not a member of "Cars".
Edit: I added the actual code that I tried to access the Register() method.
namespace Cars {
public ref class MyClass
{
void Honda(int i)
{
Cars::Register();
}
}
void Register()
{
//some code
}
}
The line Cars::Register(); do not give any error when I save but when I try to rebuild my application it gives the error below:
Error C2039 'Register': is not a member of 'Cars'
Error C3861 'Register': identifier not found
Just to note that when I put Register() inside the MyClass, everything works well (for some reason I just need to put it outside the class)
Thanks!

There are 2 issues in your code:
Missing ; at the end of the definition for ref class MyClass.
Register() should be defined (or at least declared) before calling it.
Fixed version:
namespace Cars
{
// Defintion:
void Register()
{
//some code
}
public ref class MyClass
{
void Honda(int i)
{
Cars::Register();
}
};
}
Or alternatively:
namespace Cars
{
// Declaration:
void Register();
public ref class MyClass
{
void Honda(int i)
{
Cars::Register();
}
};
// Definition:
void Register()
{
//some code
}
}
Note: since you call Register within the same namespace, you can actually drop the Cars:: qualifier, i.e. simply call: Register();. You also keep it of course, if you think it improves readability.

Related

How to stub a private method of a class written in typescript using sinon

I am writing unit tests for a public method which is, in turn, calling a private method of the class written in typescript (Node JS).
Sample Code
class A {
constructor() {
}
public method1() {
if(this.method2()) {
// Do something
} else {
// Do something else
}
}
private method2() {
return true;
}
}
Now to test method1() I need to stub method2() which is a private method.
here what I am trying :
sinon.stub(A.prototype, "method2");
Typescript is throwing the error :
Argument of type '"method2"' is not assignable to parameter of type '"method1"'
Any help would be appreciated.
Thank You
The problem is that the definition for sinon uses the following definition for the stub function :
interface SinonStubStatic { <T>(obj: T, method: keyof T): SinonStub; }
This means that the second parameter must be the name of a member (a public one) of the T type. This is probably a good restriction generally, but in this case it is a bit too restrictive.
You can get around it by casting to any:
sinon.stub(A.prototype, <any>"method2");
Sometimes when the complexity of code and tests is more significant I prefer to "externalize" private methods. You can do that, that either with a (partial) class or a (partial) interface.
it('private methods test', async () => {
// original class
class A{
public method1():string{
if(this.method2()) {
// Do something
return "true";
} else {
// Do something else
return "false";
}
}
// with private method
private method2():boolean{
return true;
}
}
// interface that makes the private method public
interface IAExternalized{
method2():boolean;
}
// class that makes the private method public
class APrivate implements IAExternalized{
// with public method
method2():boolean{
return true;
};
}
// test before mocking
let test:A = new A();
let result:string = test.method1();
result.should.be.equal("true");
// let's mock the private method, but with typechecking available
let stubMethod2:sinon.SinonStub = sinon.stub(<IAExternalized><unknown>(A.prototype), "method2").returns(false);
result = test.method1();
result.should.not.be.equal("true");
result.should.be.equal("false");
// access private method of an object through public-interface
let testPrivate:IAExternalized = <IAExternalized><unknown>test;
let result2:boolean = testPrivate.method2();
result2.should.not.be.equal(true);
result2.should.be.equal(false);
});
NOTE: If you control the code you are testing, you do not need to double code, prone to mistakes, but you can make your class implement the interface. To convert standard (without private) interface into "externalized" you can extend it with public methods.
export interface IAExternalized extends IAPrivate {
method2():boolean
};

Haxe: Native Interface properties implementable?

I've got this compiletime errors when I make some class implement an interface with properties that have been fromerly defined in some native sub class, like openfl.display.Sprite. It occurs when I'm targeting flash, not js.
Field get_someValue needed by SomeInterface is missing
Field set_someValue needed by SomeInterface is missing
Field someValue has different property access than in SomeInterface (var should be (get,set))
In contrast, there's no problem with interface definitions of 'native' methods or 'non-native' properties. Those work.
Do I have to avoid that (not so typical) use of interfaces with haxe and rewrite my code? Or is there any way to bypass this problem?
Thanks in advance.
Example:
class NativePropertyInterfaceImplTest
{
public function new()
{
var spr:FooSprite = new FooSprite();
spr.visible = !spr.visible;
}
}
class FooSprite extends Sprite implements IFoo
{
public function new()
{
super();
}
}
interface IFoo
{
public var visible (get, set):Bool; // Cannot use this ):
}
TL;DR
You need to use a slightly different signature on the Flash target:
interface IFoo
{
#if flash
public var visible:Bool;
#else
public var visible (get, set):Bool;
#end
}
Additional Information
Haxe get and set imply that get_property():T and set_property(value:T):T both exist. OpenFL uses this syntax for many properties, including displayObject.visible.
Core ActionScript VM classes (such as Sprite) don't use Haxe get/set, but are native properties. This is why they look different.
Overriding Core Properties
If you ever need to override core properties like this, here is an example of how you would do so for both Flash and other targets on OpenFL:
class CustomSprite extends Sprite {
private var _visible:Bool = true;
public function new () {
super ();
}
#if flash
#:getter(visible) private function get_visible ():Bool { return _visible; }
#:setter(visible) private function set_visible (value:Bool):Void { _visible = value; }
#else
private override function get_visible ():Bool { return _visible; }
private override function set_visible (value:Bool):Bool { return _visible = value; }
#end
}
Overriding Custom Properties
This is not needed for custom properties, which are the same on all platforms:
class BaseClass {
public var name (default, set):String;
public function new () {
}
private function set_name (value:String) {
return this.name = value;
}
}
class SuperClass {
public function new () {
super ();
}
private override function set_name (value:String):String {
return this.name = value + " Q. Public";
}
}
Need to provide the method signatures in an Interface. Currently its just a property declaration.
The error message is saying it all.
Field get_someValue needed by SomeInterface is missing
Field set_someValue needed by SomeInterface is missing
Hopefully that helps.

How to set members of mocked object

I remember reading an example which shows how to set member of a mocked object, for ex:
MyClass mockedClass = mock(MyClass.class);
//and something like this to set `someVariable` with some value
Mokito.set(mockedClass.someVariable, actual_value_intended_to_be_set);
Unfortunately I am not able to find that link again. Can someone give a reverence to
such examples or explain it here ?
If you want your mock's outward behavior to look like mockedClass.someVariable has actual_value_intended_to_be_set, you can write:
when(mockedClass.getSomeVariable()).thenReturn(actual_value_intended_to_be_set);
Happy mocking!
Is 'this' perhaps what you are looking for?
public class MyClassTest {
#InjectMocks private MyClass mockedClass;
#BeforeMethod(groups = { "unit" })
public void setup() throws Exception {
mockedClass = new MyClass();
MockitoAnnotations.initMocks(this);
Mockito.when(getSomeVariable()).thenReturn(actual_value_intended_to_be_set);
}
#Test(groups = { "unit" })
public void testMyClass() throws Exception {
//almost too trivial an example since you just setup this.
Assert.assertEquals(getSomeVariable(), actual_value_intended_to_be_set);
}
}
It creates your MyClass object and sets the return value as well.

Inheritance and method invocation through an interface instance

I've been reading "The C# Programming Language. 4th Edition" and found the following code sample:
interface I<T>
{
void F();
}
class Base<U>: I<U>
{
void I<U>.F() {...}
}
class Derived<U,V>: Base<U>, I<V>
{
void I<V>.F() {...}
}
...
I<int> x = new Derived<int,int>();
x.F();
Authors state that after calling x.F() the method in Derived will be invoked, because
"Derived<int,int> effectively reimplements I<int>"
I've checked with C# 4.0 compiler and found that this statement actually invokes the method in Base. Can you explain such behaviour?
Thanks in advance.
edit: here is the working code used for check:
using System;
interface I<T>
{
void F();
}
class Base<U>: I<U>
{
void I<U>.F()
{
Console.WriteLine("F() in Base");
}
}
class Derived<U,V>: Base<U>, I<V>
{
void I<V>.F()
{
Console.WriteLine("F() in Derived");
}
}
public class MainClass
{
public static void Main()
{
I<int> x = new Derived<int,int>();
x.F();
}
}
It outputs "F() in Base", so I don't know where I am wrong.
Because both Base and Derived interface from I.
void I<V>.F() {...} The method may be called/triggered from "Derived" but is executing the method defined in the interface.
void F();

how to avoid change of class on assigning derived class object to base class object in c# 4?

Hello from C# and OOP newbie.
How can I avoid change of class on assigning derived class object to base class object in c#?
After i run code bellow i get this response
obj1 is TestingField.Two
obj2 is TestingField.Two
I expected that i will lose access to derived methods and properties (which I did) after assigning reference but I did not expect change of class in midcode :S
using System;
namespace TestingField
{
class Program
{
static void Main(string[] args)
{
One obj1 = new One();
Two obj2 = new Two();
obj1 = obj2;
Console.WriteLine("obj1 is {0}", obj1.GetType());
Console.WriteLine("obj2 is {0}", obj2.GetType());
Console.ReadLine();
}
}
class One
{
}
class Two : One
{
public void DoSomething()
{
Console.WriteLine("Did Something.");
}
}
}
While you are right, you will lose access to members declared in the derived type, the object won't suddenly change it's type or implementation. You can access only members declared on the base type, but the implementation of the derived type is used in the case of overriden members, which is the case with GetType, which is a compiler generated method which automatically overrides the base class's implementation.
Extending your example:
class One
{
public virtual void SayHello()
{
Console.WriteLine("Hello from Base");
}
}
class Two : One
{
public void DoSomething()
{
Console.WriteLine("Did Something.");
}
public override void SayHello()
{
Console.WriteLine("Hello from Derived");
}
}
Given:
One obj = new Two();
obj.SayHello(); // will return "Hello from Derived"
GetType is a virtual method gives you the dynamic type of the object.
I think you want the static type of the variable. You can't get this by calling a method on the object referenced by the variable. Instead just write typeof(TypeName), which is typeof(One) or typeof(Two) in your case.
Alternatively in your subclass you can use a new method which hides the original one instead of overriding it:
class One
{
public string MyGetType() { return "One"; }
}
class Two : One
{
public new string MyGetType() { return "Two"; }
}
class Program
{
private void Run()
{
One obj1 = new One();
Two obj2 = new Two();
obj1 = obj2;
Console.WriteLine("obj1.GetType(): " + obj1.GetType());
Console.WriteLine("obj2.GetType(): " + obj2.GetType());
Console.WriteLine("obj1.MyGetType(): " + obj1.MyGetType());
Console.WriteLine("obj2.MyGetType(): " + obj2.MyGetType());
}
}
Result:
obj1.GetType(): Two
obj2.GetType(): Two
obj1.MyGetType(): One
obj2.MyGetType(): Two
You haven't "changed class". The type of the variable obj1 is still One. You have assigned an instance of Two to this variable, which is allowed since Two inherits from One. The GetType method gives you the actual type of the object currently referenced by this variable, not the type of the declared variable itself.

Resources