While I was using class, I found that some attributes, especially the ones which are boolean, are often read by other instances. For example,
class Node{
private:
int item;
bool visited;
public:
bool isVisited(){return visited;}
void bar(){
...
visited=true;
...
}
};
class Graph{
private:
vector<Node> nodes;
public:
void bar(int idx){
if(nodes[idx].isVidited()){
...
nodes[idx].foo();
...
}
}
}
In that case if visited is only changed by the methods of the class Node, then the access controller of the attribute visited shouldn't always be private in perspective of reading. What if there is an access controller 'readonly' that is opened to reading, closed to writing? I think that is useful when defining state attributes. Will there be any side effects?
Have you tried marking the Graph class as friend inside the Node class?
This facilitates accessing the private members of the Node class by the Graph class.
In some languages, there is getter/setter which works as an api of a private value.
It seems like a public value, but internally the methods control the private member variable, not the code with '=' operator itself.
//TYPESCRIPT
class Foo{
private _name:string
constructor(n:string){this._name=n}
get name(){return this._name}
//set name(n:string){this._name=n}
}
const foo=new Foo('Jack jack')
console.log(foo.name) //[LOG]: "Jack jack"
foo.name='hudson' //[ERR]: Cannot set property name of #<Foo> which has only a getter
The code above shows how a readonly property is set. There is only a getter which delivers exactly the same value of the private member variable '_name', but since setter is not defined, only the class itself can change the value and is not able to edit from outside of the class.
Related
How can the compiler know what method is an object calling?
lets say for example:
class Person
{
string name;
int age;
void walk()
{
// do something with name and age
}
}
so I already know that it actually translate to a method which takes the instance itself as the first parameter, but how can the object itself access it?
do all objects of class person point somewhere where all the class methods are, and maybe even static variables (and methods)?
I have this UML diagram
Ad this is the corresponding C++ code
//Parent class Flight
class Flight
{
private:
int callNumber;
Airplane plane;
vector<Passenger> passengers;
public:
//Constructor
Flight();
//Functions
int getCallNum();
void setCallNum();
Airplane getPlane();
//What parameters are taken in these functions.
//I know they are of type Airplane and passenger but are they vectors?
void setPlane(Airplane);
void addPassenger(Passenger);
void removePassenger(Passenger);
};
//Airplane class, child of Flight
class Airplane : public Flight
{
private:
int firstClassSeats;
int economySeats;
public:
//Constructor
Airplane();
//Functions;
int getFirstClassSeats();
int getEconomySeats();
void setFirstClassSeats();
void setEconomySeats();
};
//Passenger class, child of FLight
class Passenger : public Flight
{
private:
string name;
int age;
string address;
public:
//Constructor
Passenger();
//Functions
string getName();
int getAge();
string getAddress();
void setName(string);
void setAge(int);
void setAddress(string);
};
I wonder:
do constructors of all classes run when an object of either parent or base class is created?
Can base class access functions or data of child classes?
I do not know how set plane function in parent class would look like. Would it take an object of type Airplane as an argument? Similarly, will addpassenger function in parent class take a vector of type Passenger as an argument?
In short
If A inherits B (or A specializes B), then you should be able to say A is a (kind of) B. When in doubt, prefer object composition over inheritance.
More details
The parameters taken by the member functions, are the parameters that you indicate for the operations in the diagram. No parameter in the diagram leads to no parameters in the code.
The inheritance here is ambigous. There is no inheritance in your diagram. There is some in your code, but it does not make so much sense: is a passenger really a flight? E.g. can a passenger fly, have a crew, etc.?
If the inheritance would be suitable, as a general rule in C++: the constructor of an object is always called when the object is created. In case of inheritance, all the constructors of the class hierarchy are invoked, starting with the base constructor, until the most derived constructor (the rules can be more tricky, for example in case of multiple inheritance). In UML, the rules on constructors are not fully specified as far as I know.
By default, a class can only access public members of another class. If a class is derived from a base class (in UML: if a class is a specialisation of a more general class), the derived class has only access to the public and protected members of the base class. Try to avoid protected, since it's a frequent cause of nasty bugs.
WHen implementing in C++ an UML class diagram, there is a tricky issue about the types of the properties and arguments, because C++ has a value semantic: if you pass an Airplane as argument, the original airplane object is copied. Same if you have an Airplane property. However, in UML, properties and associations have a reference semantic (except for datatypes), meaning that the airplane argument would still refer to the same original airplane. So in your specific case, you'd probably want to pass a reference or a (smart) pointer to an Airplane.
I m preparing a class in my flutterfire project and their I want to use some method Which can't change further so that I want to know consept of static keyword in Dart ?
"static" means a member is available on the class itself instead of on instances of the class. That's all it means, and it isn't used for anything else. static modifies members.
Static methods
Static methods (class methods) don’t operate on an instance, and thus don’t have access to this. They do, however, have access to static variables.
void main() {
print(Car.numberOfWheels); //here we use a static variable.
// print(Car.name); // this gives an error we can not access this property without creating an instance of Car class.
print(Car.startCar());//here we use a static method.
Car car = Car();
car.name = 'Honda';
print(car.name);
}
class Car{
static const numberOfWheels =4;
Car({this.name});
String name;
// Static method
static startCar(){
return 'Car is starting';
}
}
static keyword in dart used to declare a variable or method that belongs to just the class not the instants which means the class has only one copy of that variable or method and those static variables(class variables) or static methods(class methods) can not be used by the instances created by the class.
for example if we declare a class as
class Foo {
static String staticVariable = "Class variable";
final String instanceVariable = "Instance variable";
static void staticMethod(){
print('This is static method');
}
void instanceMethod(){
print('instance method');
}
}`
the thing here to remember is static variables are created only once and every instance crated by the class has different instance variables. therefore you can not call static variables form the class instances.
following codes are valid,
Foo.staticVariable;
Foo().instanceVariable;
Foo.staticMethod();
Foo().instanceMethod();
there for following codes will give errors
Foo().staticVariable;
Foo.instanceVariable;
Foo().staticMethod;
Foo.instanceMethod
Use of static variables and methods
you can use static variables when you have constant values or common values that are relevant for the class.
you can read more here - https://dart.dev/guides/language/language-tour#class-variables-and-methods
public class CanvasManager : MonoBehaviour
{
public static CanvasManager Instance; // = lobby
[SerializeField]
private LobbyFunction _lobbyFunction;
public LobbyFunction LobbyFunction
{
get { return _lobbyFunction; }
}
...
below is one of the reference
private void Start()
{
GameObject lobbyCanvasGO = CanvasManager.Instance.LobbyFunction.gameObject;
...
I am confused that is it necessary to have the same name of canvasmanager that it is declared , and why there is no error when I sayCanvasManager.Instance.LobbyFunction ,it made me confused since LobbyFunction is belonged to CanvasManager, not Instance.
Finally , sometimes ,
private LobbyFunction _lobbyFunction;
private LobbyFunction LobbyFunction
{
get { return _lobbyFunction; }
}
Sometimes,
private LobbyFunction _lobbyFunction;
public LobbyFunction LobbyFunction
{
get { return _lobbyFunction; }
}
Thanks for your patience reading this, and your help would be greatly appreciated, thanks!
Your class is named CanvasManager, but you cannot statically access it right away.
You created a static member variable in CanvasManager, which holds a reference to a CanvasManager. This is called the singleton pattern.
You can only access static members without a class instance. But in the case of singletons, you create a single instance of the class (usually assigned in Start() or in getInstance() (lazy) after checking if it exists) which you can then access statically through "Instance".
Now, Instance is a static variable holding a reference to a single instance of CanvasManager. So, you can then access non-static members and functions of CanvasManager, if you access "Instance".
Think about it like this:
CanvasManager local_instance = new CanvasManager();
local_instance.non_static_member = value; // this works
CanvasManager.static_member = value; // this works
CanvasManager.non_static_member = value; // won't work.
And now one step further, you access the instance via CanvasManager.Instance.*
CanvasManager.Instance.non_static_member = value; // works!
Explanation of static vs non-static:
normal variables:
Variables needs memory. So usually you create 5 instances of CanvasManager and each instance can have different values. Because each instance reserves memory for each Variable. But if you want to change one, you need to explicitly talk to that instance. You could manage them in a List or by having multiple variables in Code like manager1, manager2...
Think of it as books, where each copy can be modified (write notes into it)
static variables
If you create a static variable, the memory is reserved once for the Class. You can then directly get/set this static variable from anywhere in Code without the need of a Reference to an instance.
Think of it as an online blog, where changes are applied for everyone, being accessible from everywhere. The text exists once in the blog database.
Singletons:
If you only want a single CanvasManager and not 5, you could attach it to any GameObject and access it. But every other script needs a reference, like public CanvasManager my_manager which you need to assign in inspector. As an alterantive, you could use
GameObject.Find("CanvasManagerObject").getComponent<CanvasManager>()
in each script... If only there was a better way to access this CanvasManager from everywhere...
The singleton pattern allows you to get a reference to a single, nonstatic instance of the CanvasManager, while it doesn't even need a GameObject it can attach to.
Naming
You are talking about "it has to have the same name" - this is not true. You can name the instance whatever you like. CanvasManager.MyCustomlyNamedInstance would work too. But the MyCustomlyNamedInstance must be a static variable in the CanvasManager class, or any other class. You could have a GameManager that manages your instances, so GameManager.MyCanvasManagerInstance would work too.
I know that, normally, 'objects' of a class cannot access the private members. But in the function definition of a copy constructor, you use objects to access the private members members. How come?
eg:-
class Sample {int i,j;
public:
Sample(int a, int b)
{i=a;j=b;}
Sample(Sample &S)
{j=s.j;i=s.i;}
}
It is the same class. A different instance, but the same class.
private means that the member is only visible within the class - including other instances.