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

Class Inheritance in Carbon

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

Introduction

Hello Ninja! Do you want to learn about class inheritance in the Carbon language? If yes, get ready, as we will cover this topic in detail. Inheritance is a crucial object-oriented programming concept. Its main advantage is that it allows you to reuse your code. We will start with an introduction to the Carbon programming language and then learn about class inheritance in Carbon. 

class inheritance in carbon

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++. To resolve some of the flaws of C++, Carbon was launched in July 2022. The idea to create Carbon is similar to how Microsoft made Typescript to improve JavaScript and Kotlin to address Java's shortcomings. 

carbon logo

Google initiated this project. It is currently accepting contributions from developers on GitHub. Carbon has 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 best 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 known as an "object." We can create multiple objects using the same class.    

Look at the image that follows to understand it better.

classes and objects

Classes in Carbon are declared using the keyword "class." A class in Carbon can have members and methods.

Look at the example that follows to see how we declare classes in Carbon.

Example: We will create a class called "Sum." It will have a member variable and a method. We will create an object and invoke the "Add" method defined in the class.

Implementation in Carbon

package codingninjas_sample api;
 
// Declaring a class named Sum
class Sum {
 
    // Member variable of class Sum
    var p: i32;
 
    // Method of class Sum
    fn Add[me: Self](var x: i32) -> i32 {
        var sum: i32 = me.p + x;
        return sum;
    }
}
 
// Driver function
fn Main() -> i32 {
 
    // Creating an object of class Sum
    var obj: Sum = {.p = 23};
 
    // Calling the method of class Sum using the object
    var sum: i32 = obj.Add(27);
    
    // The sum obtained will be 23 + 27 = 50
    Print("After addition: {0}" , sum);
    return 0;
}

Output

output of example of class

Inheritance

Inheritance refers to a class's capacity to derive features and traits from another class. It is one of the key object-oriented programming fundamentals. 

Class inheritance in Carbon occurs when we create a new sub-class from an existing class. The new class that inherits traits from another class is known as a "derived class," "child class," or “sub-class.” The already existing class from which we inherit is called a “base class,” “parent class,” or “superclass.” The new class inherits all of its superclass's properties. It may have its properties too, but it doesn’t change the properties of its superclass. 

inheritance

The derived class can access all the methods defined in the base class except those made private.

Let us now look at the benefits of using class inheritance in Carbon.

Pros of Inheritance

The following are the benefits of using class inheritance in Carbon:

  • It allows us to reuse our code, i.e., we do not have to write the same code multiple times. We can inherit it in another class.
     
  • It makes the code clear and easy to understand.
     
  • We can override the methods of the base class with inheritance. It allows us to build a useful version of the base class function in the derived class.
     
  • Inheritance results in lower maintenance and development expenses.
     
  • We can also make some of the base class data private so that the derived class cannot alter it.

Cons of Inheritance

Some disadvantages of using class inheritance in Carbon are listed below.

  • The increased time and effort required by the program to jump across all levels of overloaded classes reduce the execution speed. 
     
  • Changes in the base classes will also impact the behavior of the derived class.
     
  • The excessive use of inheritance complicates the code.
     
  • We can only use the derived class with the base class.

Extending Classes

On an opt-in basis, Carbon enables inheritance through a class hierarchy. Classes are final by default, which means they cannot be inherited. We have to use the introducer base class or abstract class while declaring a class to achieve inheritance. 

Syntax:

base class Abc { ... }


We can get a derived class by extending the base class.

Syntax:

base class Def extends Abc { ... }
class Hij extends Def { ... }

// Class Hij is final; we cannot extend it further.


An abstract class is a particular type of class that can not be instantiated. You must extend (or inherit) an abstract class to use it. We create abstract classes in Carbon using the “abstract” keyword before a  class.

Syntax:

abstract class A { ... }

// It is not permitted to create objects (instantiation) of class A.


Currently, Carbon allows only the inheritance of a single derived class from a single base class (single inheritance). In the future, Carbon will also support multiple-class inheritance.

Know about Single Inheritance in Java in detail.

Virtual Functions

A "virtual method" (or "virtual function") is a member function that we declare in a base class but override in a derived class. In Carbon, a virtual method is declared by including the virtual override keyword before a function declaration.

Syntax:

base class A {
    virtual fn Overrideme[me: Self]() -> i32 { 
        return 7; 
    }
}

Types of Virtual Functions

There are three virtual keywords in Carbon. These keywords are used before the declaration of a function. They are as follows:

The Virtual keyword

The “virtual" keyword denotes that a method is a member function declared in the base class. This method has an implementation in the base class, but in derived classes, that implementation can be overridden. 

It is required to utilize a single pointer to refer to all of the objects of the various classes. As a result, we make a pointer to the base class, which can refer to all derived objects. However, when the base class pointer holds the address of the derived class object, the base class function is always executed. To execute the derived class function using the base class pointer, we use the “virtual" keyword.

The Abstract Keyword

The “abstract” keyword is an abbreviation for "abstract virtual," although, in C++ it is referred to as "pure virtual." It doesn’t have an implementation in the base class; this method must be overridden in a derived class. Only abstract classes can have unimplemented abstract methods.

The Impl Keyword

The “impl” keyword indicates a method that overrides a virtual or abstract method in the base class and has an implementation specific to this class. If this is a base class, the method is still virtual and can be overridden again in the derived classes. The compiler can detect whether the derived class utilizes the incorrect signature or spelling by using a keyword when overriding.

That was all about class inheritance in carbon. Now, let us look at some FAQs.

Frequently Asked Questions

Does Carbon support C++ interoperability?

Carbon is compatible with C++ programs and facilitates migration. The Carbon toolchain will be able to compile C++ code. Hence, it does support C++ interoperability.

What is Inheritance?

Inheritance refers to a class's capacity to derive features and traits from another class. It is one of the most important object-oriented programming concepts. 

When was Carbon launched?

Carbon-lang was introduced as an open-source, experimental heir to C++. To resolve some of the flaws of C++, Carbon was launched in July 2022.

What is the need for class inheritance in Carbon?

The main advantage of class inheritance in Carbon is that it allows us to reuse the code. Instead of repeating the same code, we can inherit the traits of the base class into the derived class.

Is Carbon a compiled language or an interpreted language?

Carbon is a free and open-source programming language that is statically typed and compiled.

Conclusion

In this article, we have discussed class inheritance in Carbon. We started with a brief introduction to the Carbon programming language, then learned about class inheritance in Carbon, virtual functions, types of virtual functions in Carbon, and more. 

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!

Happy coding, Ninja!

Topics covered
1.
Introduction
2.
Carbon Programming Language
3.
Classes in Carbon
3.1.
Implementation in Carbon
3.2.
Output
4.
Inheritance
5.
Pros of Inheritance
6.
Cons of Inheritance
7.
Extending Classes
8.
Virtual Functions
9.
Types of Virtual Functions
9.1.
The Virtual keyword
9.2.
The Abstract Keyword
9.3.
The Impl Keyword
10.
Frequently Asked Questions
10.1.
Does Carbon support C++ interoperability?
10.2.
What is Inheritance?
10.3.
When was Carbon launched?
10.4.
What is the need for class inheritance in Carbon?
10.5.
Is Carbon a compiled language or an interpreted language?
11.
Conclusion