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

Classes and Objects in Carbon

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

Introduction 

Hello ninja, A few essential topics are shared among all different programming languages. Such as variables, keywords, data typesclasses, objects, etc.

Classes and Objects in Carbon

In this article, we will deal with classes in Carbon which will also cover common concepts applied to any other programming language. We will also understand what objects in Carbon are.

About Carbon

Carbon programming language is an open-source and general-purpose object-oriented language developed by Google. It was introduced in July 2022 at a conference held in Toronto. It is a language that advances C++. It can work with the existing C++ systems, making switching to Carbon easier.

About Carbon

Carbon is still in its experimental phase right now.

Why Choose Carbon

There are currently 250-2500 programming languages worldwide, so the reasons to learn and use Carbon are as follows:

  • Solid language foundations.
     
  • If you are familiar with C++, then Carbon is elementary for you.
     
  • Fast performance. 
     
  • Scalable libraries.
     
  • Interoperates with existing C++.

Why Carbon Over C++

Carbon is similar to C++. Even the performance of these languages matches by 100%.  

The difference is that Carbon provides a better developer experience. This is because, in Carbon, you can extend libraries easily as there is a massive decrease in the technical debt of the existing libraries.

We will now discuss one of the essential concepts: objects in Carbon. 

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

Objects in Carbon

Objects in carbon are a fundamental concept but also easy to learn. Objects in carbon are entities with two components:

  • State - consists of all the parts of an object.
     
  • Behaviour - tells the purpose of the object.
     

Objects in Carbon are instances of classes in Carbon which we will discuss in the next section. Objects in carbon help to allocate memory to the class. This means that there is no memory allocated to a class. Instead, memory is always allocated to objects in the Carbon of a class.

Let us take a real-world example for a better understanding

Example

Look at the picture of a bike given below.

 picture of a bike

As you can see, it is a picture of a cycling bike. The bike here is a class. The bike's components, such as wheels, brake, seat, pedal, handle, etc., are all in the object's state. The behaviour of the object bike is its mobility. 

Now, if we want to make a program to represent this bike, It will look something like the below-given code. 

Code Implementation

package bike api;

class Bike
{
    var wheel;
    var handle;
    var seat;
    var pedal;
}

Explanation 

We have described what a bike would look like using the class “bike” in the above example. The objects in Carbon in the above example are the wheel, handle, seat, and pedal. Objects in Carbon are always written using the keyword “var.” 

Here the memory is not allocated to the class bike. Instead, it is assigned to the objects: “wheel,” “handle,” “seat,” and “pedal” under the class name “bike.”

Classes in Carbon

User-defined types used as a blueprint for objects are known as classes in Carbon.

Why are classes in Carbon called blueprints?

We say so because classes in Carbon consist of the state and behavior of objects in Carbon which later can be used by calling out the class for various purposes. 

Classes in Carbon

Let us take a real-world object example for better understanding.

Example

We will use the example of a table and write a program for a class called a table.

Code Implementation

package tableexample api;

class Table
{
    var legcount: i32;
    var leglength: i32;
    var platformwidth: i32;
    var platformthickness: i32;
}

Explanation

The class name is “table”, which consists of the properties(state) of the table object. This class tells us how the desired table looks or can be built. Thus it provides a blueprint of the table, which is an object.

NOTEi32 is used for the integer data type of 32 bits.

As we can see in the above example, there are several different parts of classes in Carbon.

Components of classes in Carbon

Components of classes in Carbon are:

  • Data members.
     
  • Member functions.
     
  • Class methods.
     
  • Alias.
     
  • Let.
     
  • Another class.
     

We will discuss these in detail in the below section.

Members of a Class

As discussed above, there are two components of classes in Carbon. We will learn about both of them one by one.

Data Members

Data members in classes in Carbon are the data variables that represent the objects in Carbon. 

Look at the code given below:

package sumexample api;

class Digits
{
    var a: i32;
    var b: i32;
}


In this example, “a” and “b” are the data members of the class “digits”, which represent the object properties(state.)

Member Functions

Member functions of classes in Carbon are also known as class functions. 
These functions are applied to the class itself and not to the objects. Thus even if there are no objects inside a class in Carbon, member functions will still operate. 
The operation of these functions is similar to static functions in C++. 

Look at the code given below:

package sumexample api;

class Digits
{
    var a: i32;
    var b: i32;

    fn Origin() -> Digits {
        return {.a=0, .b=0};
    }
}


As you can see, we have declared a function called ”Origin” in the scope of the class. Several other functions, like Get<variable name>, etc., are used in Carbon, which is also used in examples in this article.

NOTEwe can also use “Self” instead of writing the class name while defining a function in the scope of classes in Carbon.

We can call this function later in the program using the class name and the function name with a dot (.) in between the names followed by a parenthesis ().
For examplewe will write Digits.Origin() to call out the origin function of the digits class in the above-given example.

NOTEWhenever there is a member function defined in the scope of classes in Carbon, the execution of the program is such that the objects are defined or read by the compilers first and then the function, irrespective of the layout of the program.

Class Methods

Class methods are class functions and operate similarly to member functions of classes in Carbon. These are defined just like a class function but with a “me” parameter inside square brackets[] before the regular parentheses().

Look at the code given below:

package sumexample api;

class Digits
{
    var a: i32;
    var b: i32;

    fn GetA[me: Digits]() -> i32 {
        return me. a;
    }
}


As you can see, we have used the “me” parameter to define class methods almost the same way we defined member functions.

Aliases Declaration 

Alias in classes in Carbon is used to change the existing data member name(object name). 
Look at the code given below:

package sumexample api;

class Digits
{
    var a: i32;
    var b: i32;
    alias a = c;
}


As you can observe, we have used “alias” to change the data member name from a to c. Thus these members of classes in Carbon are beneficial when writing extensive programs. 

NOTEwe cannot write alias a = 2 because the right side of the alias is not a value. Both sides of the alias are the data members' names, the former being the old name and the latter the new name. 

Let Declaration

The let declaration in classes in Carbon works the same way we use let while solving mathematical problems. It is used to specify the value of the data members(objects).

Look at the code given below:

package sumexample api;

class Digits
{
    var a: i32;
    var b: i32;
    let a: i32 = 64;;
}


As you can observe, we have defined the value of “a” data member using the let declaration. It might not seem helpful here, but when we write programs taking different values for the same data member, this declaration plays an important role.

Another Class

We can define another class in the scope of a class in Carbon. It is used to define a nested class in classes in Carbon. By nested class, we mean a class under a class that has the properties of a class but works like any other member of classes in Carbon.
Look at the code below:

package Car api;

class Car
{
    var doors: i32;
    var seats: i32;
    var wheels: i32;

    class Colour{
        var carcolour: String;
        var seatcolour: String;
    }
}


As you can observe, we have defined a class called “Colour” in the scope of class “car,” making the class “color” a nested class. This nested class operated like other members of the main class. 

Let us now discuss how to use all the different class members by declaring them in the next section.

Declaration of Classes

Declaration of classes means using the different kinds of members of a class in classes in Carbon for various purposes.

First, let’s learn how to declare an introductory class in Carbon.

Class Declaration 

The points to remember while writing classes in Carbon are given below:

  • The keyword “class” should be lowercase.
     
  • The class name should be in capital case or pascal case.
     
  • Insert curly brackets{} to define a class’s body inside it.
     
  • Objects are defined using the “var” keyword in Carbon.
     
  • The object name should not have any spaces.
     
  • The data type specification of any object is done by inserting a colon(:) after the object name.
     
  • End all the expressions using semicolons (;).

Code Implementation

package sumexample api;

class Digits{
    var a: i32;
    var b: i32;
}
fn Main () -> i32 {
    var x: Digits = {.a=200, .b=300};
    Print("Result: {0}", x.b - x.a);
    return 0;
}

Output

output image

Explanation

We have specified the class name as “Digits” and included “a” and “b” as objects using the keyword “var.” We have also set the data type for the values of these objects by inserting a colon after the object name. We also inserted a semicolon after each expression to send the expressions. We calculated the difference between “a” and “b” data members.

Member Function Declaration 

The points to remember while declaring a class method in classes in Carbon is:

  • All the points necessary to declare an introductory class in Carbon(discussed in the above “class declaration” section.)
     
  • Write “fn” to specify it is a function.
     
  • Write the function name in a capital case.
     
  • Use arrows proceeded by class name to indicate the function to operate on the class data members.
     
  • Set a return value using “.<data member name>”.
     
  • End all the expressions inside the function with a semicolon (;).
     
  • Call out the function by setting a variable to “<class name>.<function name>()”.

Code Implementation

package sumexample api;

class Digits{
    var a: i32;
    var b: i32;

    // Member fuction declaration.
    fn Original() -> Digits {
        return {.a=0, .b=300};
    }
}
fn Main() -> i32{

    // Calling out the member function.
    var x: Digits= Digits.Original();

    Print("Result: {0}", x.b);
    return 0;
}

Output

output image
 

Explanation

We have written a member function called “Original” in the scope of the class “Digits.” As you can see, we have set the return values using a dot such as “.a=0”. We have called out the function by creating a variable x and assigning it the value “Digits.Original()”.

Class Method Declaration 

The points to remember while declaring a class method in classes in Carbon is:

  • All the points necessary to declare an introductory class in Carbon(discussed in the “class declaration” section.)
     
  • All the points necessary to declare a member function in Carbon(discussed in the above “member function declaration” section.)
     
  • Write “me” for methods in Carbon in square brackets after the function name and before the parentheses.
     
  • Use a semicolon between me and the class name.
     
  • Set a return value for the method function using a dot(.) between me and the variable name. 
     
  • Call out the class method by using the class methods function name.

Code Implementation

package sumexample api;

class Digits{
    var a: i32;
    var b: i32;

    // Using class methods in Carbon.
    fn GetA[me: Digits]() -> i32 {
        return me.x;
    }
}
fn Main () -> i32 {
    var x: Digits = {.a=200, .b=300};

    // Calling out the class method to print the value of A.
    Print("Result: {0}", p.GetA());
    return 0;
}

Output

output image

Explanation

We have written this code to print the value of “a” data member of the class “Digits”. As you can see, we have used me inside square brackets. We have also set a return value using a dot such as “me.x” and used the function GetA() to call out the class method in the scope of the main function.  

Application of Classes

The application of classes is extensive, making it one of the essential concepts of any object-oriented programming. The main use of the class is that we don’t have to define an object’s properties again and again throughout the program whenever we are specifying objects of the same kind.

Let’s look at a real-world example for better understanding.

cars example

This is a picture of two cars. Both cars have the same number of wheels, doors, seats, etc. So if we create a program to identify if the picture is a car or not, we will have to declare these properties again and again under conditional statements. This will make our code lengthy and congested. Instead, we use classes where we declare the object's properties once and call out the class as needful. 

Now it's time to discuss some FAQs.

Know What is Object in OOPs here in detail.

Frequently Asked Questions

What does Carbon provide the programmers that make it unique?

Carbon offers programmers modern practices, like generics, modular code organization, and simple syntax. Carbon matches the performance of C++ and alongside provides ease to extending the existing libraries, which is not possible in C++.

What are the variables in Carbon?

Whenever we want to store data, it requires a particular memory location. To call or use these stored data, we need to give these locations a variable name.

Is carbon programming language bi-directional?

Carbon language is Bi-directional as it allows us to call C++ language code from Carbon and also Carbon language code to C++.

Why are data types necessary in Carbon?

Data Types are required for carbon or any programming language because they help interpreters or compilers understand the type of any value.

How are arrays declared in the Carbon language?

To declare arrays in Carbon language using array types and array size. For example, var arr: [i32; 5] = (1,2,3,4,5);

Conclusion

In this article, we learned what objects in Carbon are. We also understood what classes in Carbon are while covering members of a class. We also learned how to declare a class along with the class application.

To learn more about the Carbon programming language, refer to,

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!

Topics covered
1.
Introduction 
2.
About Carbon
2.1.
Why Choose Carbon
2.2.
Why Carbon Over C++
3.
Objects in Carbon
3.1.
Example
3.2.
Code Implementation
3.2.1.
Explanation 
4.
Classes in Carbon
4.1.
Example
4.2.
Code Implementation
4.2.1.
Explanation
5.
Members of a Class
5.1.
Data Members
5.2.
Member Functions
5.3.
Class Methods
5.4.
Aliases Declaration 
5.5.
Let Declaration
5.6.
Another Class
6.
Declaration of Classes
6.1.
Class Declaration 
6.2.
Code Implementation
6.2.1.
Output
6.2.2.
Explanation
6.3.
Member Function Declaration 
6.4.
Code Implementation
6.4.1.
Output
6.4.2.
Explanation
6.5.
Class Method Declaration 
6.6.
Code Implementation
6.6.1.
Output
6.6.2.
Explanation
7.
Application of Classes
8.
Frequently Asked Questions
8.1.
What does Carbon provide the programmers that make it unique?
8.2.
What are the variables in Carbon?
8.3.
Is carbon programming language bi-directional?
8.4.
Why are data types necessary in Carbon?
8.5.
How are arrays declared in the Carbon language?
9.
Conclusion