How to access a non-public variable in a base class? - oop

I'm in a method of a derived class, loosely as follows:
Class Base
{
private:
int variableIWantToAccess;
}
Class Derived : public Base
{
public someMethod() {
variableIWantToAccess++; <<-----ERROR
}
How do I access the variable that's declared in the base class? I'm unable to access it because it is private.

You should declare it as protected instead of private.
Protected members of a class are accessible for the class descendants only.

Leave the field private and create a pair of protected getter / setter methods instead (for the same reasons you wouldn't expose a public field).
Class Base
{
private:
int variableIWantToAccess;
protected:
int GetVariable() { return variableIWantToAccess; }
void SetVariable(int var) { variableIWantToAccess = var; }
}

Related

Point to the function created in C# project from generic typename in C++/CLI

C++/CLI :
public interface class ITest{
public:
virtual void doSomething (){
}
}
public ref Base {
...........
...........
}
generic <typename T> where T : ITest
public ref Derived : Base{
public:
virtual void doNothing (){
}
}
public ref AnotherClass {
public:
generic<class T> where T : Base
static int justDoThis(){
//Problem!!
}
}
C# :
In C# there are two classes A and B. A inherits from the ITest and B inherits from Derived where A is used as the typename. Also, B has a private variable of type A. So, from main function AnotherClass.justDoThis<B>() is called where B is passed as the generic type.
"//Problem!!" Part :
Now I have to create a new instance of B in this section and also access the A which is private variable in B.
So if I take your paragraph of description of the C# code:
class A : ITest {}
class B : Derived<A>
{
private A someVariableOfTypeA;
}
class Program
{
void Main(string[] args)
{
AnotherClass.justDoThis<B>();
}
}
And the problem is that you want to do this:
public ref AnotherClass {
public:
generic<class T> where T : Base
static int justDoThis()
{
// Problem!!
Something^ actuallyB = gcnew Something();
A^ a = actuallyB->someVariableOfTypeA;
}
}
Issue #1: You can allow creation of new objects of the generic type by specifying gcnew as another generic constraint. (In C#, this would be new.) This will require that the generic type have a default (i.e., parameterless) constructor, which you can access with the normal gcnew.
generic<class T> where T : Base, gcnew
static int justDoThis()
{
T^ t = gcnew T();
}
Issue #2: You cannot access private variables within an object. That's what private means. If you want to give justDoThis access to the A object, then add an appropriate public method or property to Base. The method or property would return type ITest. You could also put that method/property on a new interface (perhaps named IHaveAnITestAccessorMethod), and add that as another generic constraint, and B satisfies all the constraints.
Note that it won't do any good to make the variable public on type B: justDoThis doesn't know about B, it only knows about T, which is a Base with a no parameter constructor.
Disclaimers:
I didn't check my syntax with a compiler.
Yes, you can do anything with reflection, but that's a bad design. Don't do that, fix your code the right way.

ninject binding for specify class

if I have the interface interfaceA
public interface IInterfaceA
{
void MethodA();
void MethodB();
}
and I have the classA
class ClassA:IInterfaceA
{
public void MethodA()
{
}
public void MethodB()
{
}
}
it's ok that I use ninject's bind,but when it comes that I have a method that called MethodC,I think the method should only exists in classA(just for classA) and should not be defined in InterfaceA,so how to use ninject'bind when just calling like this:
var a = _kernel.get<IInterfaceA>()
should I convert the result into ClassA ? (is that a bad habbit?) or there are another solution
Usually this is needed when you want interface separation but need both interfaces to be implemented by the same object since it holds data relevant to both interfaces. If that is not the case you would be able to separate interfaces and implementation completely - and then you should do so.
For simplicitys sake i'm going to asume Singleton Scope, but you could also use any other scope.
Create two interfaces instead:
public interface IInterfaceA {
{
void MethodA();
}
public interface IInterfaceC {
void MethodC();
}
public class SomeClass : IInterfaceA, IInterfaceC {
....
}
IBindingRoot.Bind<IInterfaceA, IInterfaceB>().To<SomeClass>()
.InSingletonScope();
var instanceOfA = IResolutionRoot.Get<IInterfaceA>();
var instanceOfB = IResolutionRoot.Get<IInterfaceB>();
instanceOfA.Should().Be(instanceOfB);
Does this answer your question?

VB.Net and access via a variable of an interface type

How do I make the properties of a class available in an inheriting class, for a variable that is declared to be the type of one of the interfaces implemented by that class?
What I have done so far is to create an abstract class MyAbstract with the keyword MustInherit and in the inheriting class MyInheritingClass I have added inherits and then the name of the abstract class. Now this is all fine, but in my inheriting class, if I create an interface on that class MyInterface and use that interface elsewhere in my code, I have then found that I cannot see the properties from my abstract class, on the variable declared with that interface.
Am I doing something wrong here, or is there something else that I need to do?
An example would be as follows:
Public MustInherit Class MyAbstract
Private _myString as String
Public Property CommonString as String
Get
Return _myString
End Get
Set (value as String)
_myString = value
End Set
End Property
End Class
Public Class MyInheritingClass
Inherits MyAbstract
Implements MyInterface
Sub MySub(myParameter As MyInterface)
myParameter.CommonString = "abc" ' compiler error - CommonString is not a member of MyInterface.
End Sub
'Other properties and methods go here!'
End Class
So, this is what I am doing, but when I use MyInterface, I cannot see the properties of my Abstract Class!
Unless I've completely misunderstood your question, I'm not sure why you are confused by this behavior. Not only is that how it should work, but that is also how it works in c#. For instance:
class Program
{
private abstract class MyAbstract
{
private string _myString;
public string CommonString
{
get { return _myString; }
set { _myString = value; }
}
}
private interface MyInterface
{
string UncommonString { get; set; }
}
private class MyInheritedClass : MyAbstract, MyInterface
{
private string _uncommonString;
public string UncommonString
{
get { return _uncommonString; }
set { _uncommonString = value; }
}
}
static void Main(string[] args)
{
MyInterface test = new MyInheritedClass();
string compile = test.UncommonString;
string doesntCompile = test.CommonString; // This line fails to compile
}
}
When you access an object through any interface or base class, you will only ever have access to the members that are exposed by that interface or base class. If you need to access a member of MyAbstract, you need to cast the object as either MyAbstract or MyInheritedClass. This is true in both languages.

Override accessor or assign the value in constructor

I have a question on object-oriented programming.
If there is a attribute which has different value in sub-classes. It should create a abstract accessor in the super-class, then override it in the sub-classes. Or create a protected instance variable in base-class, and assign the default value in the sub-class constructor?
Let's see the code example code:
Choice 1:
class BaseClass {
public abstract int GetFoo();
}
class SubClass {
public int GetFoo() {
return -1;
}
}
Choice 2:
class BaseClass {
protected int _foo;
public int GetFoo() {
return _foo;
}
}
class SubClass {
public SubClass() {
_foo = -1;
}
}
Or any ideas?
I would go with the first approach of providing a getter that can be overridden in the derived classes to provide a different value, instead of creating protected members in my class which are also package-private and violate the encapsulation principle.

Design: classes with same implementation but different method names

I have multiple classes that have similar implementation for different named methods:
class MyClassX
{
public int MyClassXIntMethod(){}
public string MyClassXStringMethod(){}
}
class MyClassY
{
public int MyClassYIntMethod(){}
public string MyClassYStringMethod(){}
}
the methods inside the classes have similar implementation but because the method's names are different (due to 3rd party constraints) i cannot use inheritance.
I'm looking for an elegant solution that would be better than implementing the same functionality over and over again.
The classic answer IMHO is use the adpater pattern for every 3rd party calling party.
Don't apply blindly but see if it is a good fit first.
class MyClassXAdapter
{
IMyInterface _myImpClass
public int MyClassXIntMethod(){ return _myImpClass.IntMethod()}
public string MyClassXStringMethod(){ return _myImpClass.StringMethod() }
}
class MyClassYAdapter
{
IMyInterface _myImpClass
public int MyClassYIntMethod(){ return _myImpClass.IntMethod()}
public string MyClassYStringMethod(){ _myImpClass.StringMethod() }
}
class MyClassImplementation :IMyInterface
{
public int IntMethod(){}
public string StringMethod(){}
}
And whats the problem in using composition?
class MyClassY
{
private MyClassX myclx;
public int MyClassYIntMethod()
{
return myclx.MyClassXIntMethod();
}
public string MyClassYStringMethod(){...Similarly here...}
}
Why not simply create a common super class, and let each "MyClass_" call that common function? You can have a different program signature and still reuse the same codes pieces. Without copy and paste the same code again.
class MyClassX extends MyClassGeneric
{
public int MyClassXIntMethod(){}
public string MyClassXStringMethod(){}
}
class MyClassY extends MyClassGeneric
{
public int MyClassYIntMethod(){ return MyClassIntMethod();}
public string MyClassYStringMethod(){return MyClassStringMethod();}
}
class MyClassGeneric
{
protected int MyClassIntMethod(){ /*...... logic .....*/ return 0; }
protected string MyClassStringMethod(){/*...... logic ....*/return "";}
}
Real world example.
Without "software patternitis". (I apply software patterns, very useful, but, I'm not adicted to them).
collections.hpp
#define pointer void*
class Collection {
protected:
VIRTUAL bool isEmpty();
VIRTUAL void Clear();
}
class ArrayBasedCollection: public Collection {
protected:
int internalInsertFirst(pointer Item);
int internalInsertLast(pointer Item);
pointer internalExtractFirst(int Index);
pointer internalExtractLast(int Index);
}
class Stack: public ArrayBasedCollection {
public:
OVERLOADED bool isEmpty();
OVERLOADED void Clear();
// calls protected "internalInsertFirt"
void Push(pointer Item);
// calls protected "internalExtractLast"
pointer Pop(pointer Item);
}
class Queue: public ArrayBasedCollection {
public:
OVERLOADED bool isEmpty();
OVERLOADED void Clear();
// calls protected "internalInsertFirt"
void Push(pointer Item);
// calls protected "internalExtractFirst"
pointer Pop(pointer Item);
}
Cheers.