C++ Classes Vs. C# Classes - Limiting access to classes with class modifiers
(Page 3 of 6 )
Gone are the days where you could only limit access to specific methods and members within a class and not the actual class itself. C# allows us to limit access to class instantiation by simply appending that classes declaration with a class access modifier, just like we did for methods and members in the previous section.
In C++ we can't restrict access to a class as a whole. Take a look at this C++ class declaration:
class Car
{
public: Car();
Car(Car &c);
virtual ~Car();
private: int numCars;
Car* previous;
Car* next;
};
We have two types of access specifiers here: public and private. If the Car class is derived or instantiated from within our code, then there's no way that we can make it so that it must be inherited only from within the same source code file, or even make it so that it can't be used as the base class for a derived class.
In C#, this has all changed. We can append our class declarations with class access modifiers to restrict both access to its internal members and methods, as well as instantiation rights. These eight access specifiers are:
- public: This class is accessible to all other classes. If a class is declared without explicitly specifying an access modifier for it, then it's public by default.
- private: Accessible only by the class in which it is declared.
- protected: Accessible only by the class in which it is declared, as well as any derived classes.
- protected internal: Accessible only by the class in which it is declared, as well as any derived classes in the same source code file.
- internal: Accessible only from within the same assembly (in C#, an assembly is a package of inter-related data that contains both code and meta data).
- sealed: Prevents a class from every being derived. If another class tries to use this class as its base class either directly or indirectly then the C# compiler will raise an error.
- abstract: Similar to the concept of a pure virtual function in C++, an abstract class can't actually be instantiated. It contains a signature, but can only be used when it is the base class of a derived class.
- new: Using the new keyword as an access modifier for a nested class allows us to hide an inherited method of a parent class by providing the compiler with a new version of that class.
For example, if I wanted to create a class that could never be used as the base class of a derived class, then I would use the sealed access modifier, like this:
sealed class Car
{
public void paintCar()
{
// Code to paint car goes here
}
}
If I wanted to create a RedCar class that is derived from the Car class like this:
internal class RedCar : Car
{
// Won't work.
}
Then the C# compiler would spit an error indicating that a sealed class cannot be inherited from:
error CS0509: 'RedCar' : cannot inherit from sealed class 'Car'Next: Virtual functions in C and C# >>
More C# Articles
More By Jordan Leverington