A class in C++ allows developers to group together related data and functions to represent an object. The document discusses the basics of classes and objects in C++, including:
- What a class is and how it can constrain and manipulate data like an int primitive.
- The components of a class declaration including data members and methods.
- How objects are instances of a class that occupy memory and can access class members.
- The importance of encapsulation through making data private and providing public accessors.
- How to define methods and access class members using the scope resolution operator.
- Best practices like placing class declarations in header files and definitions in cpp files.
The document provides an introduction to object oriented programming (OOP) compared to procedural programming. It discusses key concepts in OOP like objects, classes, attributes, methods, encapsulation. Objects contain attributes (data) and methods (behaviors). Classes are templates that define common attributes and methods for a set of objects. Encapsulation involves hiding class data and implementation details through access modifiers like private and public. Examples are provided to demonstrate how to define classes and create objects in C++ code.
The document proposes a model for entangling users' data to protect remotely stored data from server corruption. It defines six adversary classes based on the recovery algorithm (standard, public, private) and corruption method (destructive, arbitrary). It shows all-or-nothing integrity is possible in the standard-recovery model by using message authentication codes, but not in public/private models as adversaries can modify the recovery algorithm. Symmetric recovery is possible in the public model if encoding is symmetric. All-or-nothing integrity is achievable against destructive adversaries by interpolating a polynomial of the data.
The document discusses object-oriented programming and class-based design. It explains that object-oriented programming focuses on modeling real-world objects as software objects with both data fields (attributes) and methods to operate on that data. A class defines a blueprint for objects, describing their attributes and methods. Objects are instances of classes that package both data and behaviors together. The document outlines key concepts like encapsulation, inheritance, polymorphism, and UML class diagrams.
Dear students get fully solved SMU MBA assignments
Send your semester & Specialization name to our mail id :
“ help.mbaassignments@gmail.com ”
or
Call us at : 08263069601
Dear students get fully solved assignments
Send your semester & Specialization name to our mail id :
help.mbaassignments@gmail.com
or
call us at : 08263069601
This document provides an overview of object-oriented programming concepts in Python including objects, classes, inheritance, polymorphism, and encapsulation. It defines key terms like objects, classes, and methods. It explains how to create classes and objects in Python. It also discusses special methods, modules, and the __name__ variable.
Programming in Java: Storing Data. Last delivered in 2016. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
The document discusses access modifiers in Java and their usage with variables, functions, and classes at different levels. It explains that access modifiers like private, protected, default, and public determine whether elements are visible from within the same class, package, subclass, or any class. Private is most restrictive while public is most accessible. It also covers other concepts like static methods, inheritance, polymorphism, abstract classes, interfaces and exception handling in Java.
The document provides an introduction to object oriented programming (OOP) compared to procedural programming. It discusses key concepts in OOP like objects, classes, attributes, methods, encapsulation. Objects contain attributes (data) and methods (behaviors). Classes are templates that define common attributes and methods for a set of objects. Encapsulation involves hiding class data and implementation details through access modifiers like private and public. Examples are provided to demonstrate how to define classes and create objects in C++ code.
The document proposes a model for entangling users' data to protect remotely stored data from server corruption. It defines six adversary classes based on the recovery algorithm (standard, public, private) and corruption method (destructive, arbitrary). It shows all-or-nothing integrity is possible in the standard-recovery model by using message authentication codes, but not in public/private models as adversaries can modify the recovery algorithm. Symmetric recovery is possible in the public model if encoding is symmetric. All-or-nothing integrity is achievable against destructive adversaries by interpolating a polynomial of the data.
The document discusses object-oriented programming and class-based design. It explains that object-oriented programming focuses on modeling real-world objects as software objects with both data fields (attributes) and methods to operate on that data. A class defines a blueprint for objects, describing their attributes and methods. Objects are instances of classes that package both data and behaviors together. The document outlines key concepts like encapsulation, inheritance, polymorphism, and UML class diagrams.
Dear students get fully solved SMU MBA assignments
Send your semester & Specialization name to our mail id :
“ help.mbaassignments@gmail.com ”
or
Call us at : 08263069601
Dear students get fully solved assignments
Send your semester & Specialization name to our mail id :
help.mbaassignments@gmail.com
or
call us at : 08263069601
This document provides an overview of object-oriented programming concepts in Python including objects, classes, inheritance, polymorphism, and encapsulation. It defines key terms like objects, classes, and methods. It explains how to create classes and objects in Python. It also discusses special methods, modules, and the __name__ variable.
Programming in Java: Storing Data. Last delivered in 2016. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
The document discusses access modifiers in Java and their usage with variables, functions, and classes at different levels. It explains that access modifiers like private, protected, default, and public determine whether elements are visible from within the same class, package, subclass, or any class. Private is most restrictive while public is most accessible. It also covers other concepts like static methods, inheritance, polymorphism, abstract classes, interfaces and exception handling in Java.
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
The question asks to create classes to represent publications, books, and tapes. The Publication class has title and price attributes. The Book class inherits from Publication and adds a noOfPages attribute. The Tape class inherits from Publication and adds a playingTime attribute.
The document discusses key concepts of classes and objects in C# including defining classes, adding variables and methods, member access modifiers, creating objects, constructors, static members, private constructors, and indexers. It defines classes as user defined data types that can encapsulate data as fields and functions as methods. Objects are instances of classes that allow data and methods to be accessed. Constructors initialize objects, while static members are associated with the class rather than individual objects.
The document discusses implementing classes in Java. It begins with an example class called Counter that models a tally counter. It then covers key concepts for implementing classes like instance variables, methods, constructors, and encapsulation. It provides examples of implementing a simple Counter class with methods like click(), getValue(), and reset(). It also discusses specifying the public interface of a class before implementation, using a hypothetical BankAccount class as an example.
We learned how to implement ORM in Python using peewee. This includes creating a ZooAnimal class that inherits from peewee's Model class and defines the database fields, creating a database table for the class, and saving ZooAnimal instances to the database. We also discussed useful Python concepts like properties for private attributes, importing packages, and using *args and **kwargs to allow flexible function arguments.
This document provides an overview of object-oriented programming concepts in Visual Basic, including classes, objects, fields, properties, methods, constructors, destructors, inheritance, polymorphism, and interfaces. It discusses key Visual Basic concepts like classes, objects, access specifiers, and shows examples of creating a class with fields and properties. It also covers more advanced topics such as inheritance, polymorphism, abstract classes, interfaces, and collections.
This document discusses encapsulation and methods in C#. It defines encapsulation as enclosing items within a package to prevent access to implementation details. Access specifiers like public, private, protected, internal and protected internal control the scope and visibility of class members. Methods are defined with access specifiers, return types, parameters, and a method body. Parameters can be passed by value, reference, or as output parameters. Examples demonstrate defining and calling methods as well as different ways of passing parameters.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
This document discusses input/output and exception handling in Java. It covers reading and writing text files, including using Scanner and PrintWriter classes. It provides examples of reading numbers from a file and writing them out with formatting. It also discusses different file formats like text, HTML, and XML files. Finally, it covers techniques for reading text files like reading words, characters, and lines of text.
This chapter discusses decision making, object-oriented fundamentals, inner classes, and exception handling in Java. It describes the use of if and switch statements for decision making. It also covers access specifiers, encapsulation, inheritance, polymorphism, abstract classes, interfaces, inner classes, and exceptions.
Python allows importing and using classes and functions defined in other files through modules. There are three main ways to import modules: import somefile imports everything and requires prefixing names with the module name, from somefile import * imports everything without prefixes, and from somefile import className imports a specific class. Modules look for files in directories listed in sys.path.
Classes define custom data types by storing shared data and methods. Instances are created using class() and initialized with __init__. Self refers to the instance inside methods. Attributes store an instance's data while class attributes are shared. Inheritance allows subclasses to extend and redefine parent class features. Special built-in methods control class behaviors like string representation or iteration.
The document discusses classes and methods in Java. It introduces the class as the fundamental building block of object-oriented programming in Java. A class defines the form and nature of an object by specifying its data and code. The document then discusses the general form of a class, including instance variables and methods. It provides examples of simple Box classes with instance variables like width, height, and depth. The document also discusses how to declare objects of a class and access instance variables using the dot operator. Finally, it introduces methods, how to add methods to a class, how methods can return values, and how methods can take parameters to make them more flexible and reusable.
Get More on http://www.ManzoorTheTrainer.com
This eBook contains 109 important interview questions along with answers that any web developer looking for a job on MS.Net platform needs to know. This eBook starts with two articles one of which talks about why most of the engineers are jobless and the other say the solution for it. As a technical part I have covered the following MS.Net technologies ASP.Net, C#.Net & ADO.Net and MS SQL Server.
Second edition is also on the way with focus on at least one real time example on each question.
Key features: Point to point | Simple language
Object oriented programming uses concepts like encapsulation, inheritance and polymorphism to create robust and secure code. The key concepts are:
1. Encapsulation and data abstraction which group data and functions that work on that data.
2. Inheritance allows code reusability through parent-child class relationships in multilevel and multiple inheritance.
3. Polymorphism enables one interface and different actions through inheritance.
Structures in C# are similar to classes but are value types stored on the stack. The document defines a Student struct with roll_number and Name properties, and shows how to declare a variable of the struct type, assign values to its properties, and copy one struct to another. Structs can also contain methods, as shown in the Rectangle struct example which defines a constructor, Area method, and Display method. Nested structs are also possible, like an Employee struct containing a nested Salary struct. The key differences between structs and classes are that structs are value types stored on the stack while classes are reference types.
The document discusses a software development team called Team-9 at SoftCorp that is developing a mobile email client application. The team wants to develop an email client that supports multimedia emails to address a limitation in their competitor's product, and covers topics like identifying security requirements and vulnerabilities. The team finds issues in code fragments that could lead to security threats and proposes solutions to address them. Design patterns like thin client and protected process are identified that could enhance security for the product.
130614 sebastiano panichella - mining source code descriptions from develo...Ptidej Team
This document describes a 5-step approach for mining method descriptions from developer communications:
1. Download emails/bug reports and trace them to classes and methods using heuristics like mentioning class/file names.
2. Extract paragraphs of text from the communications.
3. Trace paragraphs to methods by checking for mentions of "method" and method names.
4. Apply heuristics to score paragraphs associated with methods based on how well they describe the method, like percentage of method parameters mentioned.
5. Rank paragraphs for each method by score to select best descriptions.
This document discusses key concepts in object-oriented programming with C++ including classes, objects, access modifiers, member functions, friend functions, and inline functions. It provides examples of how to define a class with data members and member functions, how to declare objects of a class, and how to define and call member functions and friend functions. It also demonstrates how to use access modifiers like public, private, and protected and how inline functions work.
The document summarizes key concepts in object-oriented programming (OOP) such as classes, objects, access modifiers (public, private, protected), inheritance, polymorphism, and function overloading. It provides examples to illustrate class definitions and member functions, the differences between public, private, and protected access modifiers, and how inheritance and polymorphism work in OOP.
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
The question asks to create classes to represent publications, books, and tapes. The Publication class has title and price attributes. The Book class inherits from Publication and adds a noOfPages attribute. The Tape class inherits from Publication and adds a playingTime attribute.
The document discusses key concepts of classes and objects in C# including defining classes, adding variables and methods, member access modifiers, creating objects, constructors, static members, private constructors, and indexers. It defines classes as user defined data types that can encapsulate data as fields and functions as methods. Objects are instances of classes that allow data and methods to be accessed. Constructors initialize objects, while static members are associated with the class rather than individual objects.
The document discusses implementing classes in Java. It begins with an example class called Counter that models a tally counter. It then covers key concepts for implementing classes like instance variables, methods, constructors, and encapsulation. It provides examples of implementing a simple Counter class with methods like click(), getValue(), and reset(). It also discusses specifying the public interface of a class before implementation, using a hypothetical BankAccount class as an example.
We learned how to implement ORM in Python using peewee. This includes creating a ZooAnimal class that inherits from peewee's Model class and defines the database fields, creating a database table for the class, and saving ZooAnimal instances to the database. We also discussed useful Python concepts like properties for private attributes, importing packages, and using *args and **kwargs to allow flexible function arguments.
This document provides an overview of object-oriented programming concepts in Visual Basic, including classes, objects, fields, properties, methods, constructors, destructors, inheritance, polymorphism, and interfaces. It discusses key Visual Basic concepts like classes, objects, access specifiers, and shows examples of creating a class with fields and properties. It also covers more advanced topics such as inheritance, polymorphism, abstract classes, interfaces, and collections.
This document discusses encapsulation and methods in C#. It defines encapsulation as enclosing items within a package to prevent access to implementation details. Access specifiers like public, private, protected, internal and protected internal control the scope and visibility of class members. Methods are defined with access specifiers, return types, parameters, and a method body. Parameters can be passed by value, reference, or as output parameters. Examples demonstrate defining and calling methods as well as different ways of passing parameters.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
This document discusses input/output and exception handling in Java. It covers reading and writing text files, including using Scanner and PrintWriter classes. It provides examples of reading numbers from a file and writing them out with formatting. It also discusses different file formats like text, HTML, and XML files. Finally, it covers techniques for reading text files like reading words, characters, and lines of text.
This chapter discusses decision making, object-oriented fundamentals, inner classes, and exception handling in Java. It describes the use of if and switch statements for decision making. It also covers access specifiers, encapsulation, inheritance, polymorphism, abstract classes, interfaces, inner classes, and exceptions.
Python allows importing and using classes and functions defined in other files through modules. There are three main ways to import modules: import somefile imports everything and requires prefixing names with the module name, from somefile import * imports everything without prefixes, and from somefile import className imports a specific class. Modules look for files in directories listed in sys.path.
Classes define custom data types by storing shared data and methods. Instances are created using class() and initialized with __init__. Self refers to the instance inside methods. Attributes store an instance's data while class attributes are shared. Inheritance allows subclasses to extend and redefine parent class features. Special built-in methods control class behaviors like string representation or iteration.
The document discusses classes and methods in Java. It introduces the class as the fundamental building block of object-oriented programming in Java. A class defines the form and nature of an object by specifying its data and code. The document then discusses the general form of a class, including instance variables and methods. It provides examples of simple Box classes with instance variables like width, height, and depth. The document also discusses how to declare objects of a class and access instance variables using the dot operator. Finally, it introduces methods, how to add methods to a class, how methods can return values, and how methods can take parameters to make them more flexible and reusable.
Get More on http://www.ManzoorTheTrainer.com
This eBook contains 109 important interview questions along with answers that any web developer looking for a job on MS.Net platform needs to know. This eBook starts with two articles one of which talks about why most of the engineers are jobless and the other say the solution for it. As a technical part I have covered the following MS.Net technologies ASP.Net, C#.Net & ADO.Net and MS SQL Server.
Second edition is also on the way with focus on at least one real time example on each question.
Key features: Point to point | Simple language
Object oriented programming uses concepts like encapsulation, inheritance and polymorphism to create robust and secure code. The key concepts are:
1. Encapsulation and data abstraction which group data and functions that work on that data.
2. Inheritance allows code reusability through parent-child class relationships in multilevel and multiple inheritance.
3. Polymorphism enables one interface and different actions through inheritance.
Structures in C# are similar to classes but are value types stored on the stack. The document defines a Student struct with roll_number and Name properties, and shows how to declare a variable of the struct type, assign values to its properties, and copy one struct to another. Structs can also contain methods, as shown in the Rectangle struct example which defines a constructor, Area method, and Display method. Nested structs are also possible, like an Employee struct containing a nested Salary struct. The key differences between structs and classes are that structs are value types stored on the stack while classes are reference types.
The document discusses a software development team called Team-9 at SoftCorp that is developing a mobile email client application. The team wants to develop an email client that supports multimedia emails to address a limitation in their competitor's product, and covers topics like identifying security requirements and vulnerabilities. The team finds issues in code fragments that could lead to security threats and proposes solutions to address them. Design patterns like thin client and protected process are identified that could enhance security for the product.
130614 sebastiano panichella - mining source code descriptions from develo...Ptidej Team
This document describes a 5-step approach for mining method descriptions from developer communications:
1. Download emails/bug reports and trace them to classes and methods using heuristics like mentioning class/file names.
2. Extract paragraphs of text from the communications.
3. Trace paragraphs to methods by checking for mentions of "method" and method names.
4. Apply heuristics to score paragraphs associated with methods based on how well they describe the method, like percentage of method parameters mentioned.
5. Rank paragraphs for each method by score to select best descriptions.
This document discusses key concepts in object-oriented programming with C++ including classes, objects, access modifiers, member functions, friend functions, and inline functions. It provides examples of how to define a class with data members and member functions, how to declare objects of a class, and how to define and call member functions and friend functions. It also demonstrates how to use access modifiers like public, private, and protected and how inline functions work.
The document summarizes key concepts in object-oriented programming (OOP) such as classes, objects, access modifiers (public, private, protected), inheritance, polymorphism, and function overloading. It provides examples to illustrate class definitions and member functions, the differences between public, private, and protected access modifiers, and how inheritance and polymorphism work in OOP.
The document discusses object-oriented programming concepts in C# including classes, objects, encapsulation, inheritance, polymorphism, and more. Some key points:
- A class defines the structure and behavior of an object. An object is an instance of a class that allocates memory at runtime.
- Encapsulation binds data and functions into a single unit and controls access to its properties.
- Inheritance allows a derived class to inherit attributes and behaviors of the base class.
- Polymorphism allows different classes to have similarly named methods that work differently depending on the object type.
- Access specifiers like public, private, protected determine visibility of class members.
The server containing programming assignments is located at 10.203.161.7 under the ~/CPP/ directory. The document outlines various C++ programming assignments divided across multiple sessions, including writing classes, operator overloading, inheritance, polymorphism, and more. Assignments involve concepts such as memory management, pass by reference, constructors/destructors, friend functions, and virtual functions.
Friend functions and classes allow external code to access private members of a class. The document demonstrates declaring a function and class as friends of the Rectangle class to access its private length and width variables. This is done by specifying the function or class as friend within the class definition. This allows the friend function getCost() and class CostCalculator to multiply length and width to calculate the area or cost despite them being private members.
The document discusses key concepts of object-oriented programming in C++ including classes, objects, access modifiers, inheritance, polymorphism, and function overloading. It provides examples of defining classes with data members and member functions, as well as inheriting from base classes and overriding methods in derived classes. The document is intended as an introduction to important OOP concepts in C++.
Getting Started - Console Program and Problem SolvingHock Leng PUAH
The document provides an introduction to variables in C#, including value types like integers and reference types like objects. It discusses defining and assigning values to variables, and differences between static and non-static classes. Examples show creating a basic console application in C# and reading input from the keyboard or command line. The document concludes with exercises that guide learning programming concepts like type conversion, calculating averages, and sorting integers.
The document provides an introduction to variables in C#, including value types like integers and reference types like objects. It discusses defining and assigning values to variables, and differences between static and non-static classes. Examples show creating a basic console application in C# and getting input from the user via arguments or keyboard. Exercises guide practicing variable usage, type conversion, and writing simple programs to calculate averages and swap values.
The document discusses object-oriented programming concepts in C#, including classes, constructors, destructors, and access modifiers. It provides examples of how to define classes with properties, methods, and constructors. It also explains the differences between public, private, and protected access modifiers and how they control accessibility of class members both within and outside of a class. The document contains code examples demonstrating the usage of classes, constructors, and access modifiers in C#.
This document discusses object-oriented programming (OOP) concepts like classes, objects, inheritance, encapsulation, abstraction, and polymorphism in C++. It provides examples of how each concept is implemented in C++. It explains that classes are user-defined data types that contain data fields and methods. Objects are instances of classes. Inheritance allows classes to inherit attributes from other classes. Encapsulation binds data to the methods that operate on it. Abstraction hides unnecessary details and displays only essential information. Polymorphism allows one message to have multiple implementations.
This document describes steps to create an Android application that allows communication between activities using intents. It involves creating layouts for multiple activities, passing data between activities via intents, and using intents to start other applications like photo pickers. The exercises demonstrate starting a new activity to display user data, returning data from a started activity, and using an intent to pick an image from the device's photo gallery.
Inheritance allows a derived class to inherit attributes and behaviors from a base class. There are different types of inheritance including single, multiple, hierarchical, and multilevel inheritance. Multiple inheritance allows a class to inherit from more than one base class. Function and operator overloading allow defining multiple implementations of the same function or operator based on parameter types.
The document discusses the benefits of object-oriented programming (OOP). It states that OOP offers several benefits to programmers and users, including greater productivity, higher quality software, and lower maintenance costs. It then lists 25 specific advantages of OOP such as code reusability through inheritance, modularity through pre-defined classes, data hiding for security, and easier mapping of real-world problems to code.
This document provides an overview of object-oriented programming (OOP) concepts in C++. It defines key OOP concepts like class, object, inheritance, encapsulation, abstraction, polymorphism, and overloading. It provides examples to illustrate class and object, inheritance with different types, encapsulation by hiding data, and function overloading. The document was prepared by a trainee as part of a mentoring program and provides contact information for the training organization.
The document provides an agenda and overview of key concepts in object-oriented programming with Java including:
1. Class syntax such as access modifiers, static members, constructors, initializers, and the 'this' keyword.
2. Inheritance concepts like subclasses, superclasses, overriding methods, and the 'super' keyword.
3. Interfaces as contracts that can be implemented by classes to define common behaviors without implementation.
4. Nested classes including static nested classes and inner classes, as well as anonymous classes defined without a class name.
5. Enums, constructors, and initializers are also covered but examples are not shown.
This document provides an agenda and overview of key concepts in object-oriented programming with Java, including:
- Class syntax such as access modifiers, static members, and the 'this' keyword.
- Constructors, initializers, and how to call other constructors.
- Inheritance concepts like subclasses, superclasses, and using the 'super' keyword.
- Interfaces as contracts that can be implemented by classes.
- Nested classes, both static and inner classes, as well as anonymous classes.
- Enums for defining constant sets that can implement methods.
The document provides examples to illustrate each concept.
Introduction to object oriented programming conceptsGanesh Karthik
OOPS concepts such as class, object, encapsulation, inheritance, polymorphism are introduced. A class is a collection of objects that defines common properties and behaviors. An object is an instance of a class. Encapsulation binds data and methods together, abstraction hides implementation details, and inheritance allows deriving new classes from existing classes. Polymorphism allows the same message to be processed in different ways. Constructors and destructors are special methods used for object initialization and cleanup.
Sencha Roadshow 2017: Modernizing the Ext JS Class System and ToolingSencha
JavaScript is advancing and ES2015 (formerly ES6) is the foundation of its future. Sencha is committed to delivering cutting-edge technology for your applications, and supporting the evolution of JavaScript is a central part of that commitment. The expansive feature set of ES2015 formally enables coding paradigms: modules to better organize your code, classes to cleanly declare reusable units of functionality, and so much more. In this session, you'll see how Ext JS is embracing these new language and toolset features, and how they will expand your development horizons.
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
ClassesandObjects
1. yourvirtualclass.com
C++ for Beginners
Lesson 10 - Classes and Objects
Section 1: What is a Class?
- a class is a user-defined type
- just like a primitive type, a class restricts the values its data can hold
- a class enhances the data it contains by associating methods to manipulate them
Consider an int primitive:
int number = 12;
What if we needed to constrain the value of the int primitive to be less than 7. We would
have to write extra code to enforce the constraint:
int number = 7;
if (number > 6)
{
number = 6;
}
This would have to be repeated for each number:
int number = 7;
if (number > 6)
{
number = 6;
}
int number2 = 13;
if (number2 > 6)
{
number2 = 6;
}
It's very easy to make a mistake:
2. int number = 7;
if (number > 6)
{
number = 6;
}
int number2 = 13;
if (number2 < 6)
{
number = 6; // Oops! number2 is still 13!!
}
If we could define a new type that constrains the value of an
int primitive to be less than 7, we would avoid such errors :
Listing 1: IntLessThan7.cpp
#include <iostream>
class IntLessThan7
{
int value; // the data: an int primitive
public:
IntLessThan7(int arg1) // a method: the class constructor
{
value = arg1;
if (value > 6)
{
value = 6;
}
}
int getValue() // a method: an accessor
{
return value;
}
int main(int argc, char** argv)
{
IntLessThan7 number(12);
IntLessThan7 number2(13);
std::cout << “number = " + number.getValue());
Std::cout << "number2 = " + number2.getValue());
}
}
3. OUTPUT:
number = 6
number2 = 6
- We have created a class IntLessThan7 that expands the int
primitive data type by associating with a method (the class
constructor) that constrains its range
- Using class IntLessThan7it is impossible to create an int
whose value is greater than 6
Section 2: The Class Declaration
- a class declaration specifies the data and functions
present in the class
Class declarations have the following form:
class class_name
{
access_specifier_1:
variable_or_method_declaration_1;
access_specifier_2:
variable_or_method_declaration_2;
...
};
- a class declaration begins with the class keyword followed
by the class name followed by an open curly brace "{"
- data is specified using variable declarations
- the term "method" is used for functions specified within a class
- methods are specified using method (function) declarations
- the data and methods specified defined within a class
are called the class "members"
- the class declaration continues until the close curly brace "}"
and is followed by a semicolon
The following class declaration specifies a class called "Box"
whose data are three int primitives (length,width, and height) and no
methods. All three members have public access:
class Box
{
4. public:
int length;
int width;
int height;
};
Section 3: Objects
- a class declaration occupies no memory
- an object is an example (instance) of a class that contains all
data and methods specified in the class declaration
- objects occupy memory
An object declaration has the same form as a variable declaration:
int number; // declares variable "number" of primitive type int
Box toy; // declares an object "toy" of class Box
Object declaration syntax:
classname objectname;
Public members of an object can be referenced using the object name followed
by a dot "." followed by the member name
toy.length = 5;
std::cout << toy.length;
- the terms "instance variables" and "instance data" refer
to the class data created when an object is declared
- each object contains a separate copy of all instance variables
which is independent from that of any other object
Listing 2: BoxUsage.cpp
#include <iostream>
class Box
{
public:
int length;
int width;
int height;
5. };
int main()
{
Box toy; // declares an object "toy" of class Box
toy.length=5;
toy.width=4; // toy has its own copy of length, width and height
toy.height=3;
Box tools; // declares another object "tools" of class Box
tools.length=8;
tools.width=7; // tools has a separate copy of length, width and height
tools.height=6;
std::cout << "toy dimensions: " << toy.length << " "
<< toy.width << " " << toy.height << std::endl;
std::cout << "tools dimensions: " << tools.length << " "
<< tools.width << " " << tools.height << std::endl;
return 0;
}
LAB1: Write a class called House whose data is its square feet, street address,
number of rooms, and number of occupants. Use a char array for the
street address. Create several Houses in your main program, set their data
to values, and print them out.
Section 4: Access
- the outside world should see only the members of a class with which
it needs to interact
- make these members public using the "public:" access specifier
- make all other members private using the "private:" access specifier
- access specifiers can occur on any line inside a class declaration
- the access remains in effect until overridden by another
- the default access is private
class Box2
{
int length; // length is private (default access)
public: // members that follow are public
6. int width; // width is public
int height; // height is also public
private: // members that follow are private
int height2; // height2 is private
public: // members that follow are public
private: // overrides previous access,
// members that follow are now private
int height3; // height3 is private
};
- instance data should ALWAYS be declared private
- prevents the outside world from:
1)- setting the data to erroneous values
2)- using the data incorrectly
3)- seeing proprietary data
Here is the Box class with correct access:
class Box
{
int length;
int width;
int height;
};
- all instance variables are private (default access)
- need to specify methods for the outside to interact
with the instance data
Section 5: Public Class Methods
- class methods enhance class data by manipulating it
- can read and modify all class data (private and public)
- public class methods can be called by the outside world
- provide an interface (instructions on how to use the class)
to callers (also known as "clients" of the class)
Most common design:
- provide a method to read (get) each instance variable
7. - return type of the method = type of instance variable
- method returns the instance variable
- method takes no arguments
- prefix name of method with "get"
- commonly referred to as a "getter"
int getLength() // getter for length instance variable
{
return length;
}
- provide a method to modify (set) each instance variable
- one formal parameter whose type = type of instance variable
- return type of the method is void
- method assigns formal parameter to instance variable
- prefix name of method with "set"
- commonly referred to as a "setter"
- the term "accessor" refers to a setter or getter
void setWidth(int w) // setter for width instance variable
{
width = w;
}
- ENCAPSULATION:
- one of the key concepts in object oriented programming
- classes must keep instance data private and provide the accessors
necessary for clients
- allows large-scale maintainable software
- accessors can prevent instance data from being set to erroneous values
Let's say that for a box to fit into your car, its length must be 5 feet or less:
void setLength(int len) // setter for length instance variable
{
if ( len <= 5 )
{ // prevents setting length to a value
length = len; // greater than five feet
}
else
{
std::cout << "ERROR: length cannot be greater than 5" << std::endl;
8. }
}
Let's update the BoxUsage program to comply with encapsulation:
Listing 3: BoxEncapsulated.cpp
#include <iostream>
class Box
{
int length;
int width;
int height;
public:
int getLength() // getter for length instance variable
{
return length;
}
int getWidth() // getter for width instance variable
{
return width;
}
int getHeight() // getter for height instance variable
{
return height;
}
void setLength(int len) // setter for length instance variable
{
if ( len <= 5 )
{ // prevents setting length to a value
length = len; // greater than five feet
}
else
{
std::cout << "ERROR: length cannot be greater than 5" << std::endl;
}
}
void setWidth(int w) // setter for width instance variable
{
width = w;
}
void setHeight(int h) // setter for height instance variable
{
9. height = h;
}
};
int main()
{
Box toy;
toy.length=5; // ERROR: length instance variable is private
// use setter instead
toy.setLength(5);
toy.setWidth(4);
toy.setHeight(3);
Box tools;
tools.setLength(8); // erroneous value, length not set
tools.setLength(4); // good value, length updated
tools.setWidth(7);
tools.setHeight(6);
std::cout << "toy dimensions: " << toy.length; // ERROR: length instance variable is private
// use getter instead
std::cout << "toy dimensions: " << toy.getLength() << " "
<< toy.getWidth() << " " << toy.getHeight() << std::endl;
std::cout << "tools dimensions: " << tools.getLength() << " "
<< tools.getWidth() << " " << tools.getHeight() << std::endl;
return 0;
}
LAB2: Make the data in the House from LAB1 private. Write setters and getters and call
them in the main program to populate and print the data.
Section 6: Class Header Files
- the Box class is getting quite large
- makes it harder to understand what the BoxEncapsulated main program is doing
- if we had a second main program (called BoxApp2.cpp)
10. - would have to copy the class declaration into BoxApp2.cpp
- would have to maintain two copies
SOLUTION:
- place the Box class declaration in header file Box.h
- include Box.h in both BoxEncapsulated.cpp and BoxApp2.cpp
Inlining:
- when a method is DEFINED (its executable statements are listed) inside a class definition,
the method is inlined instead of called
- the contents of the method is copied to the caller at the point of call
- inlining makes an application needlessly large
class Box
{
...
public:
void setLength(int len)
{
if ( len <= 5 )
{
length = len;
}
}
...
};
int main() WHAT REALLY HAPPENS:
{
Box toy; Box toy;
toy.setLength(3); if (len <= 5) // no call occurs, method inlined
{
length = len;
}
SOLUTION:
- specify method DECLARATION in the class declaration
- place method DEFINITION in a .cpp file, which is compiled separatedly
Listing 4: Box.h
class Box
{
11. int length;
int width;
int height;
public:
int getLength(); // specify DECLARATIONS for each method
int getWidth(); // DEFINITIONS in Box.cpp
int getHeight();
void setLength(int len);
void setWidth(int w);
void setHeight(int h);
};
- note that iostream.h is not included in Box.h
- Needed in the DEFINITION of Box, not the DECLARATION
- NEVER include unnecessary header files in your own header files
- slows down your compilations
- this is an important point that is missed by MOST PROFESSIONAL
PROGRAMMERS!!
Section 7: Scope
- a scope is a region of a program
- variables only exist inside the scope in which they are declared
int quotient(int arg1, int arg2) // function quotient scope begins
{
int q = arg1/arg2; // variable q is local to function quotient
return q; // (has function quotient scope)
} // q disappears (goes out of scope)
int main()
{
int denominator = 5;
if ( denominator > 0) // if clause scope begins
{
int x = 10/denominator; // variable x is local to current if clause
std::cout << x << std::endl;
} // x disappears (goes out of scope)
return 0;
}
12. - class data exists only inside their class scope
- "::" is the C++ scope resolution operator
- use class_name:: to enter class_name scope from anywhere in your program
Listing 5: Box.cpp
#include <iostream> // iostream.h needed by Box DEFINITION
#include "Box.h" // include Box header file to obtain class DECLARATION
// specify non-standard file in double-quotes
// specify .h
int Box::getLength() // DEFINITION of the getLength() method of class Box
{ // Box:: enters the class Box scope
// inside getLength() definition (inside class Box scope)
return length; // can access class data
} // leaving class Box scope
int Box::getWidth()
{
return width;
}
int Box::getHeight()
{
return height;
}
void Box::setLength(int len)
{
if ( len <= 5 )
{
length = len;
}
else
{
std::cout << "ERROR: length cannot be greater than 5" << std::endl;
}
}
void Box::setWidth(int w)
13. {
width = w;
}
void Box::setHeight(int h)
{
height = h;
}
Listing 6: BoxEncapsulatedWithHeader.cpp
#include <iostream> // iostream.h needed by main program
#include "Box.h" // include Box header file to obtain class DECLARATION
int main()
{
Box toy;
toy.setLength(5);
toy.setWidth(4);
toy.setHeight(3);
Box tools;
tools.setLength(8); // erroneous value, length not set
tools.setLength(4); // good value, length updated
tools.setWidth(7);
tools.setHeight(6);
std::cout << "toy dimensions: " << toy.getLength() << " "
<< toy.getWidth() << " " << toy.getHeight() << std::endl;
std::cout << "tools dimensions: " << tools.getLength() << " "
<< tools.getWidth() << " " << tools.getHeight() << std::endl;
return 0;
}
Building the executable is a little more complex, but well worth it:
Compile the Box method definitions into a separate object file (.o) using -c compiler switch
g++ -c Box.cpp -o Box.o
14. Compile BoxEncapsulatedWithHeader.cpp into another object file
g++ -c BoxEncapsulatedWithHeader.cpp -o BoxEncapsulatedWithHeader.o
Link both object files into an executable
g++ BoxEncapsulatedWithHeader.o Box.o -o BoxEncapsulatedWithHeader
Execute:
BoxEncapsulatedWithHeader
OUTPUT:
ERROR: length cannot be greater than 5
toy dimensions: 5 4 3
tools dimensions: 4 7 6
Listing 7: BoxApp2.cpp
#include <iostream>
#include "Box.h"
int main()
{
Box present;
present.setLength(10);
present.setLength(9);
present.setLength(8);
present.setLength(2);
present.setWidth(20);
present.setHeight(30);
std::cout << "present dimensions: " << present.getLength() << " "
<< present.getWidth() << " " << present.getHeight() << std::endl;
return 0;
}
Building the executable:
(no need to re-compile Box.cpp)
Compile BoxApp2.cpp into another object file
g++ -c BoxApp2.cpp -o BoxApp2.o
Link both object files into an executable
g++ BoxApp2.o Box.o -o BoxApp2
15. Execute:
BoxApp2
OUTPUT:
ERROR: length cannot be greater than 5
ERROR: length cannot be greater than 5
ERROR: length cannot be greater than 5
present dimensions: 2 20 30
- Our implementation of the Box class now supports multiple main programs
without any duplication of code
LAB3: Write a class called Car with data for miles per gallon, make, and model.
Use char arrays for make and model. Make data private and provide setters
and getters. Place Car class declaration in file Car.h . Place Car class
implementation in file Car.cpp . Create a driver program called CarDriver.cpp.
Compile and link using g++ .
Section 8: Adding Other Methods to your Class
- classes can contain methods in addition to getters and setters
- methods which clients need to call must be public
- methods used internally should be private
Listing 8: Box.h
class Box
{
int length;
int width;
int height;
bool lengthInRange(); // private methods
void printLengthError(); // called only inside Box’s setLength() method
public:
int getLength();
int getWidth();
int getHeight();
void setLength(int len);
void setWidth(int w);
void setHeight(int h);
16. int computeVolume(); // public method: client’s can call to compute Box’s volume
};
Listing 9: From Box.cpp
int Box::computeVolume()
{
return length * width * height;
}
Bool Box::lengthInRange(int len)
{
return len <= 5;
}
void Box::printLengthError()
{
std::cout << "ERROR: length cannot be greater than 5" << std::endl;
}
void Box::setLength(int len)
{
if ( lengthInRange(len) )
{
length = len;
}
else
{
printLengthError();
}
}
Listing 10 : BoxApp3.cpp
#include <iostream>
#include "Box.h"
int main()
17. {
Box present;
present.setLength(10);
present.setLength(2);
present.setWidth(20);
present.setHeight(30);
std::cout << "present dimensions: " << present.getLength() << " "
<< present.getWidth() << " " << present.getHeight() << std::endl;
int volume = present.computeVolume();
std::cout << “present volume = “ << volume << std::endl;
return 0;
}
OUTPUT:
ERROR: length cannot be greater than 5
ERROR: length cannot be greater than 5
ERROR: length cannot be greater than 5
present dimensions: 2 20 30
volume = 1200
LAB4: Add an occupancy() method to the House class from LABs 1 and 2 which
Returns the quotient of the number of rooms and the number of occupants.
Write a HouseDriver program and call House’s occupancy() method from it.
Copyright 2016 YourVirtualClass.com. All rights reserved.