Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Access Control in Carbon Classes

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Hello ninja! We have an essential yet interesting topic about Carbon language for you to check out. We are talking about access control in Carbon classes. Carbon is an object-oriented programming language, like its predecessor C++. Access control in Carbon ensures encapsulation, one of the object-oriented programming concepts. As you go through this write-up, you will learn about access control in Carbon classes in detail.

access control in carbon classes

Before we begin, let us quickly look at the Carbon programming language.

Carbon Programming Language

Carbon-lang was introduced as an open-source, experimental heir to C++C++ is the most popular programming language among developers, even though there are many others. It is used by more than 4.4 million developers all over the world. To resolve some of the flaws of C++, Carbon was launched in July 2022.

carbon logo

Google initiated this project. It is currently accepting contributions from developers on GitHub. Carbon is packed with many features that C++ lacks. For instance, Carbon is a much more expressive language than C++. It supports modern generics systems, which are not there in C++, and the most attractive part is that it is much easier to learn. 

Now that we've covered the basics of Carbon language let's look at Carbon classes.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Classes in Carbon

A class is a blueprint describing the variables and methods shared by all objects of that class. Classes don’t use any extra space in memory as they are just a template. On the other hand, objects of a class take up memory space. A single instance of a class is called an "object." We can create many objects from the same class type.    

classes and objects

Classes in Carbon are declared using the keyword "class." A class in Carbon can have members and methods. Look at the following example to see how we declare classed in Carbon.

Example: In the following example, we will create a class named "Multiplication." It will have a member variable and method. We will create an object and invoke the "multiply" method defined in the class.

Implementation

package Sample api;

// Declaring a class named Multiplication
class Multiplication {

    // Member variable of class Multiplication
    var a: i32;

    // Method of class Multiplication
    fn Multiply[me: Self](var x: i32) -> i32 {
        var product: i32 = me.a * x;
        return product;
    }
}

// Driver function
fn Main() -> i32 {

    // Creating an object of class Multiplication
    var obj: Multiplication = {.a = 25};

    // Calling the method of class Multiplication using the object
    var product: i32 = obj.Multiply(4);
    Print("Product = {0}" , product);
    return 0;
}

Output

output of class in carbon

Encapsulation

Encapsulation is a method of restricting direct access to some components of an object. We use Encapsulation to restrict access to data members and methods related to a class or object. Access modifiers can be used in Carbon to ensure encapsulation. They allow programmers to define the visibility and accessibility of classes and the data and methods included within them. 

encapsulation

Let us look at Access modifiers in detail.

Access Modifiers

The access modifiers in Carbon are keywords that impose some constraints on the class members. We use Access modifiers for access control in Carbon. They prevent outside methods from directly accessing them. These are used before declaring a class. There are two types of access modifiers in Carbon. They are listed below.

  • Protected
     
  • Private
     

We will learn about them in detail further in this article. But before that, let us see what access control is.

Access Control in Carbon

All members of a class are fully visible to the public by default. Access can be controlled by including a keyword called an access modifier before the declaration. 

The reasons for making members “public” by default are as follows:

  • It is believed that most readers will be concerned with the public API of a type.
     
  • The most common private members are data fields, which have relatively simpler definitions and suffer less from the extra labeling.
     
access control in carbon

This approach has been used by many modern object-oriented languages, such as Kotlin, which is famous for its usability.

Unlike C++, access modifiers in Carbon are attached to individual declarations. This is similar to languages like C#KotlinSwift, and Java.

Let us now look at each access modifier of the Carbon language in detail.

Public Access

All the members of the Carbon classes are publicly accessible by default. Since access modifiers are used before each declaration in Carbon, it makes less sense to add a “public” keyword before every declaration. That is why we do not have an access modifier named “public” in Carbon, unlike C++.

Private Access 

The “private” access modifier is used to achieve private access. The members who are made private can only be accessed by the members within a class and any friends. Look at the following example to understand private access better.

Example: We will make a class named “Circle” and try to access the private member of that class.

Implementation

// Program to show private access control in Carbon
package Sample api;

// Declaring a class named Circle
class Circle {

  // Declaring private member of the class
  private var radius: i32;

  // Method of class Circle
  fn Area() -> i32 {
      var area: i32 = 3.14*radius*radius;
      return area;
  }
}

// Main function
fn Main() -> i32 {

  // Trying to access a private member of class
  var obj: Circle = {.radius = 25};

  // Calling the method of class Circle
  var area: i32 = obj.Area();
  Print("Area = {0}" , area);
  return 0;
}

Output

output of accessing private method outside of a class

As you can see, we encountered an error because we were trying to access a private member of class “circle,” which is not allowed.

Protected Access

The “protected” access modifier achieves protected access control in Carbon. The members who are protected can only be accessed by the members within a class, derived classes, and any friends. Consider the following example to understand how protected access control in Carbon works.

Example: We will create a base class A and its derived class B. After which, we will try to access the protected members outside of the base and derived classes.

Implementation

// Carbon program to understand protected access
package Sample api;

base class A {
 
  var a: i32;
 // Declaring protected member function
  protected fn Fun(x: i32) -> i32{
      Print(x);
  }

  // Declaring protected member variable
  protected var data: i32;
}

class B extends A {

    // Derived class can access the protected member of the base class
    var a: i32 = Fun(3);
  }
}

// Main function
fn Main() -> i32 {

  var obj: A = {.a = 10};

  // Calling the protected method of class A outside of the base and derived class
  var value: i32 = obj.Fun();
  Print("Value = {0}" , value);
  return 0;
}

Output

output of accessing protected members outside of base and derived class

In the above example, we encountered an error because we tried to access a protected function named “fun” of class A outside of the base and derived classes. That is not allowed.

Let's look at how we can use friend declaration to access private and protected members of a class from outside the class.

Friends

The keyword, “friend,” is used for making friend declarations in Carbon. A class declared friend to another class is often called a “friend class.” Friend classes in Carbon can access all the members of classes with which they are friends. This includes private and protected members as well.

Consider the following example to see how we declare friends in Carbon.

package sample api;

class A {
    var a: i32;
}

class B {
 
  // Private member of the class
  private var x: i32;
 
  // Declaring friend class
  friend A;
}

In this example, class A is a friend of class B. A can access all the members of B, including the private and protected members.

After the keyword, "friend” the name of an existing function, type, or parameterized family of types is used. In contrast to C++, it will not work as a forward declaration. The compiler resolves the name, so it may not be a template member.

This was all about access control in Carbon classes. Let's now answer some frequently asked questions.

Frequently Asked Questions

Who is the creator of the Carbon programming language?

Carbon was initially announced by Google developer “Chandler Carruth” in July 2022 at the CppNorth conference in Toronto.

Is Carbon going to be the next C++?

Carbon is the successor to C++, which was made to overcome its flaws. Carbon is currently in the experimental stage and will undoubtedly be a strong contender for the C++ successor. 

What is the use of the Carbon programming language?

Carbon is intended to promote software and language evolution while creating performance-critical software. Another primary purpose is to create simple code that is easier to read, comprehend, and write.

Is Carbon capable of compiling C++ code?

Carbon is intended to be compatible with C++ programs and to facilitate migration. The Carbon toolchain will be able to compile C++ code.

Is Carbon an interpreted language?

Carbon is a bytecode-interpreted scripting language with smart pointers for safe memory deallocation.

Conclusion

In this article, we have discussed access control in carbon classes. We have covered many topics including encapsulationaccess modifiersfriends, and different types of access controls in Carbon.

We hope this article helps you on your journey. You can try solving some Carbon problems, such as finding Fibonacci numbers in Carbon or determining whether a number is Armstrong in Carbon. You can refer to these articles related to Carbon by Coding Ninjas.

You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive programmingSystem Design, and many more!

Head to our practice platform, Coding Ninjas Studio, to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!

If you found this article helpful, remember to upvote it.

Happy coding, Ninja!

Topics covered
1.
Introduction
2.
Carbon Programming Language
3.
Classes in Carbon
3.1.
Implementation
3.1.1.
Output
4.
Encapsulation
5.
Access Modifiers
6.
Access Control in Carbon
6.1.
Public Access
6.2.
Private Access 
6.3.
Implementation
6.3.1.
Output
6.4.
Protected Access
6.5.
Implementation
6.5.1.
Output
7.
Friends
8.
Frequently Asked Questions
8.1.
Who is the creator of the Carbon programming language?
8.2.
Is Carbon going to be the next C++?
8.3.
What is the use of the Carbon programming language?
8.4.
Is Carbon capable of compiling C++ code?
8.5.
Is Carbon an interpreted language?
9.
Conclusion