Table of contents
1.
Introduction
2.
Constructors in Carbon
3.
Cases not Supported by Constructors
3.1.
Partial Facet
4.
Destructors in Carbon
5.
Order of Destruction of Members
6.
Virtual and Impl Destructor
7.
Frequently Asked Questions
7.1.
Is Carbon-lang released?
7.2.
Is Carbon language ready to use?
7.3.
Will Carbon replace C++?
7.4.
What is the purpose of the Carbon language?
7.5.
Is garbage collected in Carbon language?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

Constructors and Destructors in Carbon

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Over the years, Google has created a variety of programming languages, some of which have acquired a substantial reputation. For example, Golang (or Go) was created to enable the building of servers and distributed systems and has since been adopted by the general public. The Dart programming language, which was originally intended to be a JavaScript replacement, achieved mainstream recognition in the release of Flutter. 

Just like Golang and Dart, Google has released another programming language called Carbon. It is intended to be a successor to C++. 

constructors and destructors in carbon

This article will discuss Constructors and Destructors in Carbon. We will discuss the constructors in Carbon, along with some cases not supported by the constructor and partial facet. 

Afterwards, we will discuss the destructors in Carbon, the order of destructor members, and virtual and Impl destructors. So without further ado. Let’s get started!

Constructors in Carbon

The Constructors in Carbon work on classes. It can be base class or derived (after implementing inheritance). The constructors for a class are regular functions that return an instance of the class as output. Just like in C++, the constructor's name will be the name of its class.

In general, the constructor should return the value that was created without copying it. This means we will construct the object either in the return statement or in a returned var declaration.

constructors in carbon

Instances can be constructed by casting a struct value into the class type. Below is a pseudocode for a constructor constructed in a derived class. We will use .base member to initialize the members of immediate BaseClass.

class DerivedClass extends BaseClass {
  fn Create() -> DerivedClass {
    return {.base = BaseClass.Create(), .derived_field = ...};
  }
}


Example:

package sumexample api;
 
base class Digits{
    var a: i32;
    var b: i32;
}

class SubDigits extends Digits {
    fn Original() -> SubDigits {
        return {.a=50, .b=250};
    }
}
 
fn Main() -> i32{
 
    // Calling out the constructor function.
    var x: SubDigits= SubDigits.Original();
 
    Print("Result: {0}", x.a + x.b);
    return 0;
}


Output:

output for constructor

Explanation:

The above example shows the calling of the constructors in the Carbon language. Here, we are initialising the constructor in the subclass SubDigits, which after initialising, stores the values of a and b. The main function calls the constructor from the SubDigit subclass and does the required operation afterwards.

Cases not Supported by Constructors

There are two cases where constructors in Carbon fail to provide adequate support:

  • Users cannot create an abstract class value, which is required when the class has private fields or requires initialisation.
     
  • Users may wish to decrease the possibility of errors when invoking a method on a partially built object. Calling a virtual method before constructing the derived class is of particular significance. Thus the base class implementation is used.
     

While both of these problems are unlikely to arise, we will solve them with a specific type that is only utilised during building base classes, known as the partial facet type for the class.

Partial Facet

A partial Facet is created to overcome the cases that fail to be solved using Constructors in Carbon. The partial facet of a base class type, such as BaseClass, is denoted by partial BaseClass.

The syntax to use Partial Facet is as follows:

base class BaseClass {
  fn Create() -> partial SelfClass {
    return {.baseClass_field_1 = ..., .baseClass_field_2 = ...};
  }
}

Destructors in Carbon

A Destructor is a type of member function which is invoked immediately when an object is destroyed. When the lifetime of a value of a type expires, or we can say the scope of the variable is completed, a declared destructor function is called. 

destructors in carbon

The destructor of the class is declared using the destructor keyword.

class CNClass {
  destructor [me: Self] { ... }
}

// OR

class CNClass {
  // Can modify `me` in the body.
  destructor [addr me: Self*] { ... }
}


If a class does not include a destructor declaration, the default destructor is used.

Example:

package ExplorerTest api;
class Sum {

destructor [me: Self] {
    Print ("Calling destructor");
}

var a: i32;

fn Add [me: Self](var num: i32) -> i32
    {
        var total: i32 = me.a + num;
        return total;
    }
}

fn Main() -> i32
{
    var p1: Sum = {.a = 5};
    var total: i32 = p1.Add(5);
    Print("Total sum {0}", total);
	return 0;
}


Output:

output for destructor

Explanation:

The above program implements the destructor inside the class Sum. When we request the Add operation in the main class, the Add method is called. The Add method will add the number to itself and produce the result. In operation, the destructor is called by requesting "me.a".  

Order of Destruction of Members

A class's destructor is executed before the destructors of its data members. The data members are destroyed in the order in which they were declared. Because derived classes are destroyed before their base classes, the following is the order of operations:

  • When the derived class's destructor is called, the data members of the derived class are destroyed in the reverse order of declaration.
     
  • The destructor of the immediate base class is called, and the data members of the immediate base class are destroyed in reverse order of declaration, and so on.

Virtual and Impl Destructor

We cannot delete an instance of a derived class using a pointer of its base classes. For deleting the instance, we use a virtual destructor. A virtual destructor is a function that deletes a derived class object using a pointer of one of its base classes.

virtual destructors in carbon

We can declare the destructor of the base class using the virtual keyword. While the destructor for the derived class is declared using the impl keyword.

base class MyBaseClass {
  virtual destructor [addr me: Self*] { ... }
}

class MyDerivedClass extends MyBaseClass {
  impl destructor [addr me: Self*] { ... }
}

Frequently Asked Questions

Is Carbon-lang released?

Carbon, commonly known as Carbon-lang, was introduced as an experimental open-source successor to C++ in July 2022.

Is Carbon language ready to use?

Carbon is still an experimental language, which means some things may change with time. The official doc of Carbon states that “Carbon is not ready for use”. However, some design principles are less likely to change. 

Will Carbon replace C++?

Google's open-source Carbon programming language is not a direct substitute for C++. Instead, it is intended to be a replacement. While it may sound similar, the key difference is that it is intended to be used alongside C++.

What is the purpose of the Carbon language?

Carbon is a general-purpose programming language that is still under development. As of now, it is intended to be a successor to C++. It will be used along with C++ in game development and GUI.

Is garbage collected in Carbon language?

Carbon is intended to be C++-compatible and to communicate with C++ programming readily. As a result, Carbon does not use garbage collection and instead employs destructors.

Conclusion

This article briefly discussed constructors and destructors in Carbon. We discussed what are constructors in Carbon, along with some cases not supported by the constructor and partial facet. Afterwards, we discussed destructors in Carbon, the order of destructor members, and virtual and Impl destructors. Thus concluding our discussion on constructors and destructors in Carbon.


Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptAWS and many more! If you wish to test your competency in coding, check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

If you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. For placement preparations, you must look at the problemsinterview experiences, and interview bundles.

Nevertheless, consider our paid courses to give your career an edge over others!

Happy Learning!

Live masterclass