How non-static is accessible in static context in this program? - c#-3.0

I am having confusion with the following code:
class A
{
int x;
static void F(B b) {
b.x = 1; /* Ok,
I want to know how is this ok, in a static block how a non static
instance variables are called because as I know that static block
gets memory at compile time before execution of a single command
while non static at run time and static method accessing a non static
variable which is not created yet please elaborate me on this
*/
}
}
class B: A
{
static void F(B b) {
b.x = 1; // Error, x not accessible
}
}

Nothing gets memory at compile time. Static fields are indeed placed in the static block of memory when the type gets initialized. Call stacks for static methods are allocated at run time exactly like in case of instance methods.
Now, why static methods don't have access to the instance fields. Consider this:
class A {
public int Value;
static int GetValue() {
return Value;
}
}
There you have a class with an instance field and a static method. Now, somewhere else you try this:
var a1 = new A();
a1.Value = 5;
var a2 = new A();
a2.Value = 10;
int result = A.GetValue();
Now, if compiler allowed this, what value would the result get? 5 or 10 or something else? This just doesn't make sense, because static methods are declared for class as a whole and aren't aware of instances of this class. So in the code of static method you don't know how many (if any) instances of this class exist and can't access their instance fields.
Hope this makes a little sense.

Either you changed the code in question a bit or I didn't read very carefully. Seems like it's completely different problem right now. The variable x is indeed not accessible for the class B because of its level of protection (default in C# is private). Class A can modify X because it's declared in class A and visible to its method. Class B can't do it (you must make x protected or public for that).

Related

why we should use static keyword in dart in place of abstract?

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

Initialize and modify class variables in derived classes

I want to initialize a variable class for my Base class and modify it only in some children classes.
The initialization of this class variable is in the header:
class Base{
public:
Base();
int a = 1;
The header of my derived class is:
class ChildA : public Base{
public:
ChildA ();
int a = 2;
}
Problem
I tried to run this:
Base classe*;
classe = new ChildA();
std::cout << classe->a << std::endl;
The problem is that, instead of printing 2 as I expected, it prints 1 (value initialized in my parent class). For other derived classes, I want classe->a to still return 1.
How can I solve this?
What you are seeing are the results of upcasting - having a base class point to a derived class object.
I highly recommend you read more on the topic, but a simplified picture is that the base class "carries" the whole object (base and derived content), but can access only it's original, own content. This is why you see a value from the base class rather than the derived class.
Lippman's C++ Primer has a very comprehensive explanation of upcasting, downcasting, object slicing, and other inheritance-related concepts. This includes implementing virtual functions which give you the functionality to invoke derived class functions through an interface that's common with base.
|----------------|-----------------|
| a (for Base) | a (for ChildA) |
|----------------|-----------------|
\________________/
^
|_ classe
Sorry if my drawing is not that good! As you can see in the above picture, when you create an object of type ChildA, this object contains a part for keeping the data members of the base class (i.e. Base) and another part for the data members of derived class (i.e. ChildA). Considering the fact that you have a pointer to the base class (i.e. classe), this pointer only allows you to access the base member variables and methods. So calling classe->a, returns the Base::a for you, that is 1.
If you change the type of classe pointer into ChildA, in that case calling classe->a will return 2, because it refers to the a inside the derived class, i.e. ChildA::a.
For other derived classes, I want classe->a to still return 1. How can
I solve this?
If you need in some derived classes to access different as, it is better to have a virtual function in the base class and override the base function if needed:
class Base {
public:
Base() {}
virtual int getA() { return a; }
private:
int a = 1;
};
class ChildA : public Base
{
public:
ChildA() {}
int a = 2;
};
class ChildB : public Base
{
public:
ChildB() {}
int getA() { return a; }
private:
int a = 2;
};
Now by calling getA() on a pointer of Base or ChildA, you will have 1, but calling getA on an object of type ChildB will return 2.

Class with static linkage

If I recall correctly, static linkage means that a variable or function is local to its compilation unit. Meaning that there could be variables or functions with the same name and parameters in other compilation units.
I want this for a class.
Let's say I have multiple compilation units that need to ensure proper deletion at exit. So I use atexit handlers. But every compilation unit should put its own atexit-handler into place.
I did this by making a class like this:
class Init {
private:
static Init* self;
Init() {
std::atexit(Init::cleanup);
}
static void cleanup() {
// Do cleanup
}
};
Init* Init::self = new Init;
But if I have multiple classes called Init in various CUs the linker gets confused. And the compiler won't let me do static class Init {...}.
How do I archive my cleanup (if possible with classes that are called Init)?
You can put your class into an unnamed namespace.
Then, although types don't have linkage, the same effect is borne.
// Everything inside here is unique to this TU
namespace {
class Init { /** whatever **/ };
Init* Init::self = new Init;
}
int main()
{
// "Init" in here will refer to that which you created above
}

Difference between assign values for the variables of a class [duplicate]

This question already has answers here:
Should I initialize variable within constructor or outside constructor [duplicate]
(11 answers)
Closed 6 years ago.
What is the difference between below 2 ways of assigning values for variables of a class.
Class A{
Private Variable v = someValue;
}
vs
Class A{
private Variable v;
//constructor
public A(){
this.v = someValue;
}
}
Can someone please explain?
There is no real difference from a code execution point of view.
As a previous answer says, I prefer declaring the variable outside of the constructor; for example:
public class A {
private int aValue = 100;
}
Instead of
public class A {
private int aValue;
public A() {
this.aValue = 100;
}
}
The reason being that if you have multiple constructors, you do not have to keep writing this.aValue = 100; and you are unable to "forget" to initialize the variable in a constructor.
As others have said however, there are times when it is better to initialize the variable in the constructor.
If it will change based on values passed to it via the constructor, obviously initialize it there.
If the variable you are initializing may throw an error and you need to use try / catch - it is clearly better to initialize it in the constructor
If you are working on a team that uses a specific coding standard and they require you to initialize your variables in the constructor, you should do so.
Given freedom and none of the above, I still declare it at the top - makes it much easier to find all of your variables in one place (in my experience).
See this duplicate answer: https://stackoverflow.com/a/3919225/1274820
What is the difference between below 2 ways of assigning values for
variables of a class.
Generally nothing, but ...
class constructor is an entry point when creating a new instance, so all assignments should be done there for readability and maintainability.
When you want create a new instance you start reading a source code at the constructor. Here is an example. All informations about new instance are in one proper place.
public class C {
private int aValue;
private int bValue;
private int cValue;
private int dValue;
public C(int a, int b) {
this.aValue = a;
this.bValue = b;
this.cValue = a * b;
this.dValue = 1000;
}
}
If you look at the MSIL of this class:
namespace Demo
{
public class MyClass
{
private string str = "hello world";
private int b;
public MyClass(int b)
{
this.b = b;
}
}
}
.method public hidebysig specialname rtspecialname
instance void .ctor(int32 b) cil managed
{
// Code size 25 (0x19)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldstr "hello world"
IL_0006: stfld string Demo.MyClass::str <---- RIGHT HERE
IL_000b: ldarg.0
IL_000c: call instance void [mscorlib]System.Object::.ctor()
IL_0011: ldarg.0
IL_0012: ldarg.1
IL_0013: stfld int32 Demo.MyClass::b
IL_0018: ret
} // end of method MyClass::.ctor
You can see that the constructor is "injected" with the assignment of this.str = "hello world".
So once your code is compiled, there is no difference what so ever. Yet, there are quite a few good reasons why you should not do it (user1274820's answer has some them)

Java and main()

I'm messing around with Eclipse(and java in general) for the first time in about a year. among the things I have forgotten is the following:
I have a function (void callvote() that I am hoping will be activated by my main function (that is, automatically, relatively early in the program). I currently have it within the same class (body) as the main function itself.
I try to call it withcallvote(); and get an error, "- Cannot make a static reference to the non-static method callvote() from the type body"
my function callvote is, at the moment, in the space below main and simply says
public void callvote()
{
}
am i committing a horrible sin by putting more functions in the same class as main?
is this a relatively easy fix that I missed somehow?
What does this error mean?
Have I woken Azatoth with this code?
Thanks in advance,
Tormos
Without the static modifier callvote is implicitly an instance method - you need an instance of a class to call it.
You could mark it as static also:
public static void callvote() ...
Or create an instance of the declaring class:
MyClass instance = new MyClass();
instance.callvote();
main() is a static method, meaning you can call it directly from a class whereas non-static members can only be called from an object. In order for you to call the callvote() method you need to first instantiate an object of your class:
public static void main(String [ ] args) {
MyClass myObject = new MyClass();
myObject.callvote();
}
Another way to avoid the error is to make you callvote() method static as well, but it's usually not what you want to do (but it depends on the nature of your class and method).
This post describes some of the dangers with the overuse of static methods: Class with single method -- best approach?
Try this:
public class Main {
public static void main(String[] args) {
new Main().callvote()
}
}
the main() entry point of your java program is static. You cannot call a non static method from a static one.
So you have to instanciate your Class first and call the method after.