Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Object oriented programming

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Object oriented programming

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Class: Object Oriented Programming

A class is a user-defined data type. It consists of data members and member functions, which can be accessed and used by
creating an instance of that class. It represents the set of properties or methods that are common to all objects of one type. A
class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brands but all of them will share
some common properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and
wheels, speed limits, mileage are their properties

Object:

It is a basic unit of Object-Oriented Programming and represents the real-life entities. An Object is an instance of a Class. When
a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated. An object
has an identity, state, and behavior. Each object contains data and code to manipulate the data. Objects can interact without
having to know details of each other’s data or code, it is sufficient to know the type of message accepted and type of response
returned by the objects.

Example
//Create a class called "MyClass":
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Class Methods
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
Inside class definition
Outside class definition
In the following example, we define a function inside the class, and we name it "myMethod".
Note: You access methods just like you access attributes; by creating an object of the class and using the
dot syntax (.):

class MyClass { // The class


public: // Access specifier
void myMethod() { // Method/function
defined inside the class
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object
of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Nested Classes in C+
+
A nested class is a class that is declared in another class. The nested class is also a member
variable of the enclosing class and has the same access rights as the other members.
However, the member functions of the enclosing class have no special access to the members
of a nested class.

using namespace std;

/* start of Enclosing class declaration */


class Enclosing {
private:
int x;

/* start of Nested class declaration */


class Nested {
int y;
void NestedFun(Enclosing *e) {
cout<<e->x; // works fine: nested class can access
// private
members of Enclosing class
}
}; // declaration Nested class ends here
}; // declaration Enclosing class ends here
Constructors
A constructor in C++ is a special method that is automatically called when an object of a class is
created.
To create a constructor, use the same name as the class, followed by parentheses ():

Example

class MyClass { // The class


public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of
MyClass (this will call the constructor)
return 0;
}
Constructor Parameters

class Car { // The class


public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};

int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Access Specifiers
class MyClass { // The class
public: // Access specifier
// class members goes here
};
In C++, there are three access specifiers:
•public - members are accessible from outside the class
•private - members cannot be accessed (or viewed) from outside the class
•protected - members cannot be accessed from outside the class, however, they can be accessed
in inherited classes.
Example
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};

int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes
as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide
public get and set methods.

Access Private Members

Example

class Employee {
private:
// Private attribute
int salary;

public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
Two Important property of Encapsulation

1.Data Protection: Encapsulation protects the internal state of an


object by keeping its data members private. Access to and
modification of these data members is restricted to the class’s public
methods, ensuring controlled and secure data manipulation.

2.Information Hiding: Encapsulation hides the internal


implementation details of a class from external code. Only the public
interface of the class is accessible, providing abstraction and
simplifying the usage of the class while allowing the internal
implementation to be modified without impacting external code.
Extending without inheritance
• In c++ ,extending class by using static class and access using by its
name but In java reusability of code is desirable however in some
cases it is not to extend a particular class if it is declared as final.
Abstraction in C++
Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and hiding
the details. Data abstraction refers to providing only essential information about the data to
the outside world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that pressing
the accelerator will increase the speed of the car or applying brakes will stop the car but he
does not know how on pressing the accelerator the speed is actually increasing, he does not
know about the inner mechanism of the car or the implementation of the accelerator,
brakes, etc in the car. This is what abstraction is.

Types of Abstraction:

1.Data abstraction – This type only shows the required information about the data and
hides the unnecessary data.
2.Control Abstraction – This type only shows the required information about the
implementation and hides unnecessary information.
// C++ Program to Demonstrate the
// working of Abstraction
#include <iostream>
using namespace std;

class implementAbstraction {
private:
int a, b;

public:
// method to set values of
// private members
void set(int x, int y)
{
a = x;
b = y;
}

void display()
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
};

int main()
{
implementAbstraction obj;
obj.set(10, 20);
obj.display();
S.NO Abstraction Encapsulation

Abstraction is the process or method of gaining the


1. While encapsulation is the process or method to contain the information.
information.

In abstraction, problems are solved at the design or


2. While in encapsulation, problems are solved at the implementation level.
interface level.

Abstraction is the method of hiding the unwanted Whereas encapsulation is a method to hide the data in a single entity or
3.
information. unit along with a method to protect information from outside.

We can implement abstraction using abstract class and Whereas encapsulation can be implemented using by access modifier
4.
interfaces. i.e. private, protected and public.

In abstraction, implementation complexities are hidden While in encapsulation, the data is hidden using methods of getters and
5.
using abstract classes and interfaces. setters.
C++ Polymorphism

The word “polymorphism” means having many forms. In simple words, we can define polymorphism as
the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a
person who at the same time can have different characteristics. A man at the same time is a father, a
husband, and an employee. So the same person exhibits different behavior in different situations. This is
called polymorphism. Polymorphism is considered one of the important features of Object-Oriented
Programming.

Types of Polymorphism
•Compile-time Polymorphism
•Runtime Polymorphism
A. Function Overloading
When there are multiple functions with the same name but different parameters, then the
functions are said to be overloaded, hence this is known as Function Overloading. Functions
can be overloaded by changing the number of arguments or/and changing the type of
arguments
Below is the C++ program to show function overloading or compile-time polymorphism:

using namespace std;


class Geeks {
public:
// Function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}

// Function with same name but


// 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}

// Function with same name and


// 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y
<< endl;
}
};
C++ Operator Overloading
C++ has the ability to provide the operators with a special meaning for a data type, this ability
is known as operator overloading. Operator overloading is a compile-time polymorphism. For
example, we can overload an operator ‘+’ in a class like String so that we can concatenate two
strings by just using +.
// C++ Program to Demonstrate the // working/Logic
behind Operator // Overloading
class A {
statements;
};
int main()
{
A a1, a2, a3;
a3 = a1 + a2;
return 0; }

// This is automatically called when '+' is used with


// between two Complex objects
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
Inheritance
In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:
•derived class (child) - the class that inherits from another class
•base class (parent) - the class being inherited from
To inherit from a class, use the : symbol.

In the example below, the Car class (child) inherits the attributes and methods from the Vehicle class (parent):

Example
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};

// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};

int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
Inheritance type
• They are as follows:
• Single Inheritance.
• Multiple Inheritance.
• Multilevel Inheritance.
• Hierarchical Inheritance.
• Hybrid Inheritance.
Single Inheritance
• Single Inheritance in C++
• The inheritance in which a single derived class is inherited from a
single base class is known as the Single Inheritance
Ex. Of single inheritance
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account {
8. public:
9. float bonus = 5000;
10. };
11.int main(void) {
12. Programmer p1;
13. cout<<"Salary: "<<p1.salary<<endl; cout<<"Bonus: "<<p1.bonu
s<<endl;
return 0;
}
Multiple Inheritance in C++
• Multiple Inheritance is a feature of C++ where a class can inherit
from more than one classes.
• A class can be derived from more than one base class.
• Eg:
• (i) A CHILD class is derived from FATHER and MOTHER class
(ii) A PETROL class is derived from LIQUID and FUEL class.
Multiple Inheritance example…
#include<iostream>
using namespace std;

class A
{
public:
A() { cout << "A's constructor called" << endl; }
};

class B
{
public:
B() { cout << "B's constructor called" << endl; }
};

class C: public B, public A // Note the order


{
public:
C() { cout << "C's constructor called" << endl; }
};

int main()
{
C c;
return 0;
}
Multiple inheritance introduces potential
semantic problem
• Ambiguity in inheritance can be defined as when one class is
derived for two or more base classes then there are chances that
the base classes have functions with the same name. So it will
confuse derived class to choose from similar name functions.

A A

B c

D
Ambiguities occurs in replicated inheritance
and Shared inheritance.
• Repeated inheritance -It occurs whenever (as a result of multiple
inheritance) two or more of the ancestors of a class D have a
common parent A. D is then called a repeated descendant of A, and
A a repeated ancest or of D.
• Shared inheritance -
Inheritance is used when two classes in a program share the same
domain, and the properties of the class and its superclass should
remain the same

We can avid the extra level of indirection when accessing virtual


methods of virtual base classes in c++ if we are willing to replicate
portion of the base class.
Multilevel Inheritance

Multilevel Inheritance in C++ is the process of deriving a class from another derived class. When one class inherits another
class it is further inherited by another class. It is known as multi-level inheritance.
For example, if we take Grandfather as a base class then Father is the derived class that has features of Grandfather and then
Child is the also derived class that is derived from the sub-class Father which inherits all the features of Father.
Syntax:
// C++ program to implement
// Multilevel Inheritance

// single base class


class A {
public:
int a;
void get_A_data()
{
cout << "Enter value of a: ";
cin >> a;
}
};
// derived class from base class
class B : public A {
public:
int b;
void get_B_data()
{
cout << "Enter value of b: ";
cin >> b;
}
};
// derived from class derive1
class C : public B {
private:
int c;

public:
void get_C_data()
{
cout << "Enter value of c: ";
cin >> c;
}
Hierarchical Inheritance

Inheritance is a feature of Object-Oriented-programming in which a derived class (child class) inherits the property (data member and member
functions) of the Base class (parent class). For example, a child inherits the traits of their parents.
// C++ program for Hierarchical Inheritance
#include<iostream>
using namespace std;

class A //superclass A
{
public:
void show_A() {
cout<<"class A"<<endl;
}
};
class B : public A //subclass B
{
public:
void show_B() {
cout<<"class B"<<endl;
}
};

class C : public A //subclass C


{
public:
void show_C() {
cout<<"class C"<<endl;
}
};
Hybrid Inheritance.

Hybrid in C++ follows the following pattern - Multiple Inheritance, Single Inheritance, and Hierarchical Inheritances are combined together.
As stated earlier, in Multiple Inheritance, a sub-class derives properties from multiple superclasses.

Hybrid Inheritance in C++ is also known as multipath inheritance. This is known so due to the fact that a sub class derives or inherits
properties of the super class following various paths. Therefore, Hybrid Inheritance is generally applied where we need to apply more
than one form of Inheritance.
Mixed Inheritance
Mixin-based inheritance means that although every class (except for Object) has
exactly one superclass, a class body can be reused in multiple class hierarchies.
Value type and reference type

n certain computer programming languages, data types are classified as either value types or reference
types, where reference types are always implicitly accessed via references, whereas value type variables
directly contain the values themselves

Primitive data types, such as Booleans, fixed-size integers, floating-point values, and characters, are value types.

Objects, in the sense of object-oriented programming, belong to reference types i.e. Variable contain address of
value

Assigning to a variable of reference type simply copies the reference, whereas assigning to a variable of value
type copies the value.
str1 1004 800

public static void main()


{ abc 1004
string str1= “abc”;
print (“string 1”,str1);
string str1=”xyz”
print(str1)

}
Referance type example
• Ex. 5

• Int a=5; a

• Int &b=a; b

This is also know as alias. Multiple identifier refers to same data in


memory.
Typedef double wages =10;
Wages is alias name for double. We can use wages as double.
Wages = 10000;
How can pass references in function
• Void f1(int x)
• {
• }
• Int a=10;
• //function
• F1(a);
Order of execution

In this article, we will discuss the order of execution in the initializer list in
C++. Generally, the order of execution is from top to bottom and left to
right. But a rare condition arises where this rule fails is when the
initializer list is used in class.
What is Binding?

Binding refers to the linking between the function call and the function definition. In the code, at any point of time when a function is
called, then the program control binds to the address in memory where the function has been defined.

By default, C++ matches a function call with the correct function definition at compile time. This is called static binding. You can specify
that the compiler match a function call with the correct function definition at runtime; this is called dynamic binding.
#include <iostream>
using namespace std;

class A
{
public:
void m1()
{
cout << "m1 is invoked\n";
}

void m2()
{
cout << "m2 is invoked\n";
}
};
int main()
{
A obj;
obj.m1();
obj.m2();
return 0;
}
What is Static Binding?

Static binding happens at compile-time, i.e., the function call and the
function definition are linked during the compile time itself. So, it is also
called early binding.
This is because all the information needed to associate the function call to its
definition is available at the compile time.
When does static binding take place?
Static binding happens by default for any normal function calls in the
program. It also occurs during function overloading and operator
overloading.
class add {

public int sum(int a, int b) { When we call the same function


return a + b;
sum() from the main, it gets bound to
}

public int sum(int a, int b, int c) {


the correct definition. So, in this
return a + b + c;
case, at compile time itself, the
}
}
function call binds to the correct
public class static_binding {
public static void main(String
function depending upon the
args[]) {
add a1 = new add();
parameters passed to them.
int a, b, c;
a = 10;
b = 20;
c = 30;
System.out.println(a1.sum(a,
b));
System.out.println(a1.sum(a,
b, c));

}
}
What is Dynamic Binding?

Dynamic binding takes place during run time based on the type of object. Since it is delayed till the
run time, it is also called late binding or runtime binding. When the compiler cannot determine all the
information required to resolve a function call during compile time, these function calls are not
bound until run time.

When does dynamic binding take place?


It can be achieved with the use of virtual functions in C++ and
overridden methods in Java.
Java code for demonstrating Dynamic binding:
class Human {
// Overridden Method
public void walk() {
System.out.println("Human walks");
}
}

class Boy extends Human {


// Overriding Method
public void walk() {
System.out.println("Boy walks");
}

public class dynamic_binding {


public static void main(String args[]) {

// Reference is of Human type and object is Boy type


Human obj = new Boy();
obj.walk();// calls function of Boy class

// Reference is of Human type and object is of Human type Human


obj = new Human();
obj.walk();// calls function of Human class

}
}
C++ code for demonstrating Dynamic binding:
// C++ code to demonstrate the concept of dynamic binding
#include <iostream>
when basePtr points to the
using namespace std;
derived class object
class B
{ “derived”, it is important to
public:
// function f() is declared as virtual in the base class note that the pointer is of type
virtual void f()
{ base class and the object it
cout << "The base class function is called.\n";

};
} points to is of type derived
class D : public B
class. The function calls
{
public: basePtr->f() which gets
void f() //function overriding
{ resolved at run time, and
cout << "The derived class function is called.\n";
} hence the function f() of the
};

int main()
derived class is executed as
{
B base; // base class object
the object is of the derived
D derived; //derived class object
class. This is an example of
B *basePtr = &base; // base class pointer pointing to base class object
basePtr->f(); //calls function of base class function overriding, which is
basePtr = &derived; // base class pointer pointing to object of derived class possible because of dynamic
basePtr->f(); //calls function of derived class
binding/late binding.
return 0;
}
Difference between Static Binding and Dynamic Binding

Static Binding Dynamic Binding

It happens at the compile time. It happens at the run time.

It is also called early binding. It is also called late binding.

When all the information needed to call a function is available at the compile When the compiler cannot determine all the information to resolve the function call, dynamic binding occurs.
time, static binding occurs.

It can be achieved during normal function calls, function overloading and It is achieved with the use of virtual functions.
operator overloading.

Execution becomes faster than dynamic binding because the function call gets As the function call is resolved at run time, sometimes it leads to slower code execution.
resolved before run time.

It provides less flexibility compared to the dynamic binding. It provides more flexibility as different types of objects at runtime can be handled by a single function call
making the source code more readable.
What is the difference between virtual and non virtual functions in C++?

Non- virtual member functions are resolved statically. That is, the member
function is selected statically (at compile-time) based on the type of the pointer
(or reference) to the object. In contrast, virtual member functions are
resolved dynamically (at run-time).
// C++ program to illustrate What is vtable?
// concept of Virtual Functions
The vTable, or Virtual
#include <iostream> Table, is a table of
class base {
function pointers that
public: is created by the
virtual void print() { cout << "print base class\n"; }
void show() { cout << "show base class\n"; }
compiler to support
}; dynamic
class derived : public base {
public:
polymorphism
void print() { cout << "print derived class\n"; }
void show() { cout << "show derived class\n"; }
};
int main() A virtual function (also known as virtual methods) is a
{ member function that is declared within a base class and
base* bptr; is re-defined (overridden) by a derived class. When you
derived d; refer to a derived class object using a pointer or a
bptr = &d; reference to the base class, you can call a virtual
// Virtual function, binded at runtime function for that object and execute the derived class’s
bptr->print(); version of the method.

// Non-virtual function, binded at compile time


bptr->show();
print derived class show base class
return 0;
}
DATA TYPE
There are at least three ways to think about types which we may call the
denotational constructive and abstraction based points of view. From the
denotational point of view type is simply a set of value.
Constructive means its primitive type data type or predefine types.
From Abstraction based view ,a type is an interface consisting of set of
operation with well defined and mutually consistent semantics.
Primitive data types
• Integer
• Floating points
• Complex
• Boolean type
• Character type
• User defined ordinal type
Integer
• Integer: A data type that represents some range of mathematical
integers. Different programming languages supports different size of
integers.
• For example,
• Java includes four signed integer sizes: byte, short, int, and long.
• C has 4 different specification i.e int,short ,long and char.
Operation on Integer data object typically
include the main group
• Arithmetic operation: +,-,*,/
• Relational operation: Equal ,Not Equal,Less than,greater than etc.
• Assignment operation : =
• Bit operation: In computer programming, a bitwise operation
operates on a bit string, a bit array or a binary numeral (considered
as a bit string) at the level of its individual bits. It is a fast and simple
action, basic to the higher-level arithmetic operations and directly
supported by the processor.
• Ex. Bitwise AND ,Bitwise OR,Bitwise XOR
Floating-Point:
• Floating-Point: Floating-point data types model real numbers. Most
languages include two floating-point types, often called float and
double. The float data types are used to store positive and negative
numbers with a decimal point, like 35.3, -2.34, or 3597.34987. -
3.4e+38 to 3.4e+38. -1.7e+308 to +1.7e+308.
• Float type is the standard size, usually being stored in four bytes of memory.
• Double type is require eight memory size.
• The collection of values that can be represented by a floating-point
type is defined in terms of precision and range.
• Precision is the accuracy of the fractional part of a value, measured as the
number of bits.
• Range is a combination of the range of fractions and, more important, the
range of exponents.
Complex:
• Complex values are represented as ordered pairs of floating-point
values. It contains a imaginary number. It includes operations for
arithmetic on complex values.
For example, in Python, (8 + 2j), contains j as imaginary number.

Decimal: Decimal data types store a fixed number of decimal


digits. For example, the number 0.1.
•Boolean Types: It has only two elements, true and false. Boolean
types are often used to represent switches or flags in programs.

•Character Types: It stores a single character and requires a single


byte of memory in almost all compilers.
Character string type
• The C language does not have a specific "String" data type, the way
some other languages such as C++ and Java do. Instead C stores
strings of characters as arrays of chars, terminated by a null byte.
• A String Literal, also known as a string constant or constant string,
is a string of characters enclosed in double quotes, such as "To err is
human - To really foul things up requires a computer." String literals
are stored in C as an array of chars, terminated by a null byte. A null
byte is a char having a value of exactly zero, noted as '\0'.
• Do not confuse the null byte, '\0', with the character '0', the integer
0, the double 0.0, or the pointer NULL.
In C and C++ languate
C and C++ use char arrays to store character strings.

e.g.
char mystring[]="Parag";

ii. Java

In Java, strings are supported by the String class, whose values are constant strings, and the
StringBuffer class, whose values are changeable and are more like arrays of single characters.

e.g.
String s="Parag";
String s1=new String("Parag");
StringBuffer s2=new StringBuffer("Parag");
Table 1. Character string data types

Type Value Disk usage


Fixed length, character(n) (alias Fixed length, blank padded to length n. The default If n is equal to 16 or less (n bytes). If n is
char(n)) value of n is 1. The maximum character string size is greater than 16, disk usage is the same
64,000. as varchar(n).
Variable length, character Variable length to a maximum length of n. No blank N+2 or fewer bytes depending on the
varying(n) (alias varchar(n)) padding, stored as entered. The maximum character actual data.
string size is 64,000.
Fixed length, Unicode (alias Fixed length, blank padded to length n. The For more information, see The data types
nchar(n)) maximum length is 16,000 characters. .
String Operations
Character string operation are describe below :

i. Concatenation: Concatenation is the process of appending one string to the end of another string. You concatenate strings by
using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs

ii. Relational operation on string: strings are compared using relational operators. =, <>, ><, <, <=, =<, >, >=

iii.Substring selection using positioning subsript: For substring manipulation of a string many language provides an operation for
slecting sunstring by giving the first and last character position. In python, Next = s[1:4] this assign the character from position to 10
position of string to next variable.

iv.Substring selection using pattern matching : A pattern marching operation takes one arguments as pattern data structure in
which the pattern states the form of a desires substring. The second argument is character string that is to be examined to find a
substring matches the specified by the pattern.

v.Dynamic string: String value may static or dynamic. A static string is stored in one location
• Many string operation defined iin standard header file string.h
• Library function used for character string in c and c++ are strcpy()
Which copy and assigned the string. strcat() which concatenate one
string into another. strcmp() which compare 2 string. strlen which return
number of character.
In Java
In Java, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. For example:
Char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
• String s="javatpoint";
• In Java, strings are supported by an immutable String class, whose
value cannot be change and the mutable stringbuffer class which
values are changeable.
For Example:
String str =“Apple”
string str1=new string(“Mango”)
StringBuffer str2 =new stringbuffer(“Banana”);
• Fixed (static) length (fixed size determined at allocation)
• FORTRAN 77, Ada, COBOL
• A FORTRAN 90 example: CHARACTER (LEN = 15) NAME;
• Limited dynamic length (fixed maximum size at allocation, but actual
contents may be less)
• C and C++ char arrays: actual length is indicated by a null character
• Dynamic length (may grow and shrink after allocation)
• SNOBOL4, Perl
String Length Options

• Fixed (static) length (fixed size determined at allocation)


When string is created ,the length can be static and set, such a string is known
as static length string. For example Python and Java String class.
• Limited dynamic length (fixed maximum size at allocation, but actual
contents may be less)
Are those strings which are allowed to have varying length up to a
declared and fixed maximum set by the variable’s definition. e.g. C, C+
+.
C and C++ char arrays: actual length is indicated by a null character
• Dynamic length (may grow and shrink after allocation)
Evaluation in string
• Dealing with string array can be more clumsy that dealing with
primitive string type. E.g. assume a language that treats strings a
character array and does not have predefined function such as
strcmp() in C.Then a simple assignment operation of one string to
another would require a loop.
• Implementation of character string type
Static length string descriptor:
Data descriptor is
a structure
containing
information that describes data.
>>A descriptor for static character string type is require only during
compilation which has 3 field first is type name ,second is type length
and third is first character address.
Limited dynamic length string descriptor:
• Limited dynamic string require a run time descriptor to store both the
current length and fixed maximum length.

• There are three ways to support the dynamic allocation and de-allocation
which are required for dynamic length string.
• 1)String can be store in linked list.
• 2)Store string array of pointer to individual characters allocated in the
heap.
• 3)To store complete string in adjacent storage cell.
• 1)String can be store in linked list.
• Example 1
• Given a string s, convert it into a singly linked list and return the head /
starting pointer of the linked list.
• Input:
• s = “coding”
Output:
• c -> o -> d -> i -> n -> g
Note: We are supposed to return the address of the head of the linked list.
In this case, we are supposed to return the address of node c.
• Explanation:
• The head node of the linked list should be the first character of the string,
and so the head should be pointing to the first character of the string.
• 2)Store string array of pointer to individual characters allocated in
the heap.
3)To store complete string in adjacent
storage cell
• Strings as character arrays can be stored in two ways:
• char str[6] = "Ninja"; /*One extra for string terminator*/
• char str[6] = {‘N‘,‘i’, ‘n’, ‘j‘, ‘a‘, '\0'}; /* '\0' is string terminator */

You might also like